Does canvas element have “change” event?

后端 未结 4 1028
南笙
南笙 2021-01-17 15:41

Is there a way to attach event handler to a change of a canvas element? I need to fire a function whenever something draws anything on it.

4条回答
  •  生来不讨喜
    2021-01-17 16:24

    I would actually wrap the canvas iff needed to track these commands. Here's a simple example tracking only for a few methods:

    function eventOnDraw( ctx, eventName ){
      var fireEvent = function(){
        var evt = document.createEvent("Events");
        evt.initEvent(eventName, true, true);
        ctx.canvas.dispatchEvent( evt );
      }
      var stroke = ctx.stroke;
      ctx.stroke = function(){
        stroke.call(this);
        fireEvent();
      };
      var fillRect = ctx.fillRect;
      ctx.fillRect = function(x,y,w,h){
        fillRect.call(this,x,y,w,h);
        fireEvent();
      };
      var fill = ctx.fill;
      ctx.fill = function(){
        fill.call(this);
        fireEvent();
      };
    }
    
    ...
    
    var myContext = someCanvasElement.getContext('2d');
    someCanvasElement.addEventListener( 'blargle', myHandler, false );
    eventOnDraw( myContext, 'blargle' );
    

提交回复
热议问题