JavaScript event for canvas resize

前端 未结 5 1296
礼貌的吻别
礼貌的吻别 2020-12-16 12:17

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 a

5条回答
  •  情歌与酒
    2020-12-16 12:46

    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;
      setInterval(function(){
          if( element.height !== elementHeight || element.width !== elementWidth ){
            elementHeight = element.height;
            elementWidth = element.width;
            callback();
          }
      }, 300);
    }
    
    var element = document.getElementsByTagName("canvas")[0];
    onResize( element, function(){ alert("Woo!"); } );
    

提交回复
热议问题