我希望代理画布 API,以便我可以测试抽象方法确实绘制到画布上,但是我遇到了代理后出现错误的问题:
'strokeStyle' setter called on an object that does not implement interface CanvasRenderingContext2D
此代码已简化,但会引发相同的错误:
/** !NB: This snippet will probably only run in Firefox */
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
canvas.style.backgroundColor = '#FF0000';
var ctx = canvas.getContext("2d");
var calls = [];
var handler = {
get( target, property, receiver ) {
if ( typeof ctx[property] === 'function' ){
return function( ...args ){
calls.push( { call: property, args: args } )
return ctx[property]( ...args );
};
}
return ctx[property];
}
};
try {
document.body.appendChild(canvas);
var proxy = new Proxy( ctx, handler );
proxy.scale( 1, 1 );
proxy.strokeStyle = '#000000';
canvas.getContext = function(){
return proxy;
};
}
catch( e ) {
document.getElementById('message').innerHTML = 'Error: ' + e.message;
}
<div id="message"></div>
有什么想法吗?