-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContext.js
109 lines (102 loc) · 2.64 KB
/
Context.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
class Context {
constructor($canvas) {
this.canvas = $canvas;
this.context = this.canvas.getContext('2d');
this.$offScreenCanvas = this.canvas.cloneNode();
this.ctx = this.$offScreenCanvas.getContext('2d');
this.calls = [];
this.initMethods();
}
initMethods() {
const methods = {
save: () => this.ctx.save(),
restore: () => this.ctx.restore(),
beginPath: () => this.ctx.beginPath(),
closePath: () => this.ctx.closePath(),
drawImage: (image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) => {
this.ctx.drawImage(
image,
sx,
sy,
sWidth,
sHeight,
dx,
dy,
dWidth,
dHeight,
);
},
fill: () => this.ctx.fill(),
fillStyle: style => {
this.ctx.fillStyle = style;
},
strokeStyle: style => {
this.ctx.strokeStyle = style;
},
font: style => {
this.ctx.font = style;
},
lineTo: (x, y) => this.ctx.lineTo(x, y),
translate: (x, y) => this.ctx.translate(x, y),
lineWidth: width => {
this.ctx.lineWith = width;
},
moveTo: (x, y) => this.ctx.moveTo(x, y),
stroke: () => this.ctx.stroke(),
rect: (x, y, width, height) => this.ctx.rect(x, y, width, height),
clearRect: (x, y, width, height) =>
this.ctx.clearRect(x, y, width, height),
fillRect: (x, y, width, height) => this.ctx.fillRect(x, y, width, height),
fillText: (txt, x, y, maxWidth) => this.ctx.fillText(txt, x, y, maxWidth),
};
const scope = this;
const addMethod = (name, method) => {
scope[name] = (...args) => {
scope.record(name, args);
method.apply(scope, args);
};
};
Object.entries(methods).forEach(entry => {
const [name, method] = entry;
addMethod(name, method);
});
}
clear() {
this.clearRect(
0,
0,
this.$offScreenCanvas.width,
this.$offScreenCanvas.height,
);
this.context.clearRect(
0,
0,
this.$offScreenCanvas.width,
this.$offScreenCanvas.height,
);
}
getContext() {
return this;
}
getCanvas() {
return this.$offScreenCanvas;
}
/**
* Handles the rendering on a visible canvas. If the argument
* @param {HTMLCanvasElement} The resulting canvas
* @returns {void}
*/
renderOnCanvas(canvas) {
this.context.drawImage(canvas || this.$offScreenCanvas, 0, 0);
}
assign(k, v) {
this.ctx[k] = v;
}
record(methodName, args) {
this.calls.push({ name: methodName, args });
}
getCalls() {
return this.calls;
}
}
export default Context;