Согласившись с рекомендацией @ 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
создайте получить/набор блоки для каждого из свойств и зеркало каждого контекстных методов путем передачи всех полученных аргументов в «реальный» контекст с использованием .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()
Все имущество получить/установить и все вызовы методов направляются через метод 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