我试图“伪造”一个 Canvas ,目的是将这个伪造的 Canvas 交给一个可能是任意的框架来后处理所有的直线、曲线和 moveTo。
为了解决这个问题,我尝试了这段代码,它确实有效,但我想知道我对这个幸运镜头的运气有多大。
(function(){
function DebugCanvas(){
this._dom = document.createElement( 'canvas' );
addPropertiesToObject.call( this, this._dom );
this._fakeContext = null;
}
Object.defineProperties( DebugCanvas.prototype,
{
'constructor' : {
'value' : DebugCanvas,
'enumerable' : true
},
'getContext' : {
'value' : function( which ){
var ctx;
if( which == '2d' ){
if( this._fakeContext == null ){
this._fakeContext = new FakeContext( this._dom );
}
ctx = this._fakeContext;
} else {
ctx = this._dom.getContext( which );
}
return ctx;
},
'enumerable' : true
}
}
);
function FakeContext( debugCanvas ){
this._debugCanvas = debugCanvas;
this._realContext = debugCanvas._dom.getContext( '2d' );
addPropertiesToObject.call( this, this._realContext );
}
Object.defineProperties( FakeContext.prototype, {
'toString' : {
'value' : function(){
return '[Object FakeContext]';
},
'enumerable' : true
},
'canvas' : {
'get' : function(){
return this._debugCanvas;
},
'set' : function( c ){ return },
'enumerable' : true
}
});
function addPropertiesToObject( from ){
var description, obj;
for( var prop in from ){
obj = from;
do {
if( obj.hasOwnProperty( prop ) &&
!this.constructor.prototype.hasOwnProperty( prop ) ){
try{
description = Object.getOwnPropertyDescriptor( obj, prop );
Object.defineProperty( this.constructor.prototype, prop, description );
} catch( err ){
this[ prop ] = from[ prop ];
}
break;
}
} while( obj = Object.getPrototypeOf( obj ) );
}
};
})()
基本思想是将所有 canvas'、canvas.prototypes'(所有向上的链)、contexts' 和 context.prototypes' 属性复制到假对象的原型(prototype)中,只要它们尚未存在在那里.
最佳答案
在 JavaScript 中,您可以自由构造一个具有与原始对象相同的属性/方法的替换对象,并使用它来代替原始对象。无论哪种方式,方法调用或属性访问都是相同的,并且调用代码通常不知道其中的区别。在 javascript 中,这有时是一件非常有用的事情。
像这样的替换更复杂的部分是模拟所有方法和属性的实际行为,以便您传递给它的代码按您想要的方式工作。但是,如果您能成功做到这一点,那么它应该可以正常工作。这并不涉及运气 - 只要您对方法/属性的模拟正确,这就应该有效。
关于javascript - 伪造 Canvas ——这可行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12340965/