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.
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' );