同意@ K3N的建議來包裝上下文。
下面是一些代碼,我抓住了我的CanvasRendingContext2D記錄顯示,你很快就能開始包裹CanvasRendingContext2D
的:
function LoggedContext(canvas) {
var self = this;
this.canvas=canvas;
this.context=canvas.getContext('2d');
this.imageURLs=[];
this.fillStyles=[];
this.logs=[];
this.commands=[];
this.funcs={};
this.init(self);
}
在LoggedContext.prototype.init
方法,創建的get/set塊各性能和互成鏡像通過使用.apply
將所有接收到的參數傳遞給「真實」上下文來處理上下文方法。
LoggedContext.prototype.init=function(self){
// create get/sets for properties
var properties=['strokeStyle','lineWidth','font','globalAlpha',
'globalCompositeOperation','shadowColor','shadowBlur',
'shadowOffsetX','shadowOffsetY','lineCap','lineJoin',
'miterLimit','textAlign','textBaseline'];
for(var i=0;i<properties.length;i++){
(function(i) {
Object.defineProperty(self, i, {
get: function() {
return this.context[i];
},
set: function (val) {
this.log(i,val,true);
this.context[i]=val;
}
})
})(properties[i]);
}
// create mirror methods that pipe arguments to the real context
var methods = ['arc','beginPath','bezierCurveTo','clearRect','clip',
'closePath','fill','fillRect','fillText','lineTo','moveTo',
'quadraticCurveTo','rect','restore','rotate','save','scale','setTransform',
'stroke','strokeRect','strokeText','transform','translate','putImageData'];
for (var i=0;i<methods.length;i++){
var m = methods[i];
this[m] = (function(m){
return function() {
this.context[m].apply(this.context, arguments);
this.log(m,arguments);
return(this);
};}(m));
}
// mirror methods that have return values
var returnMethods = ['measureText','getImageData','toDataURL',
'isPointInPath','isPointInStroke','createImageData'];
for (var i=0;i<returnMethods.length;i++){
var m = returnMethods[i];
this[m] = (function(m){
return function() {
return(this.context[m].apply(this.context, arguments));
};}(m));
}
// In this example code ...
// These Properties & Methods requiring special handling have
// been removed for brevity & clarity
//
// .fillStyle
// .strokeStyle
// .drawImage
// .createLinearGradient
// .createRadialGradient
// .createPattern
} // end init()
所有屬性get/set和所有的方法調用都是通過LoggedContext.prototype.log
方法引導。
你的目的,你既可以使您的調整了get/set塊或方便地進行中.log
方法的調整,因爲一切都是通過.log
方法管道。
LoggedContext.prototype.log=function(command,Args,isProperty){
var commandIndex=this.commands.indexOf(command);
if(commandIndex<0){
this.commands.push(command);
commandIndex=this.commands.length-1
}
if(isProperty){
this.logs.push([commandIndex,Args]);
}else{
this.logs.push([commandIndex,Array.prototype.slice.call(Args)]);
}
}
非常感謝您的參與!我會去這個方向。 – Noitidart
非常感謝那篇關於'apply'的筆記,我不知道它是慢的。我會確保不這樣做。 – Noitidart
非常感謝,它的工作完美! https://github.com/Noitidart/NativeShot/blob/editor-revamp/resources/scripts/editor.js#L4423-L4544 – Noitidart