rampion rampion - 1 year ago 161
Javascript Question

JavaScript event for canvas resize

It appears that altering the dimensions of a canvas clears any drawing already done on that canvas.

Is there an event that fires on canvas resize, so I can hook it and redraw when it occurs?

Answer Source

You usually don't want to strictly check for a resize event because they fire a lot when you do a dynamic resize, like $(window).resize in jQuery and as far I'm aware there is no native resize event on elements (there is on window). I would check it on an interval instead:

function onResize( element, callback ){
  var elementHeight = element.height,
      elementWidth = element.width;
      if( element.height !== elementHeight || element.width !== elementWidth ){
        elementHeight = element.height;
        elementWidth = element.width;
  }, 300);

var element = document.getElementsByTagName("canvas")[0];
onResize( element, function(){ alert("Woo!"); } );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download