I’m trying to add some code to every method called on the canvas context. I am trying to do this so I can add each command to an array of commands. This is the code I would think works (but doesn’t):
var canvas = Object.getPrototypeOf(document.createElement('canvas').getContext('2d'));
for(p in canvas){
if(canvas.hasOwnProperty(p)){
var original = canvas[p];
canvas[p] = function(){
//extra code to be run
return original.apply(this,arguments);
}
}
}
This seems to me like it should work, but it doesn’t. If I use this code in an example, I get a NOT_SUPPORTED_ERR: DOM Exception 9
The problem you’re suffering from is the fact that variables aren’t block scoped.
When your function runs, it updates the context prototype so that each function calls the same function
original, which is the last element owned by the original prototype. In this case, that iswebkitGetImageDataHD.This means when you call
ctx.beginPath();you really callctx.webkitGetImageDataHD();. This method expects 4 arguments and since it didn’t get them it throws the DOM Exception 9.Since JavaScript doesn’t support block scope, you have to force a scope change using a function. Modifying your example, we can create a new function where
originalis a fixed value:Find a working demo here: http://jsfiddle.net/bnickel/UG9gF/