blob: 590034a4a3259f9bbe575e470ea09c20ca7cf771 (
plain)
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
|
class Canvas {
constructor(rootId) {
const root = document.getElementById(rootId);
this.element = document.createElement('canvas');
this.context = this.element.getContext('2d');
this.fillWindow();
window.addEventListener('resize', () => this.fillWindow());
root.appendChild(this.element);
this.ondraw = null;
/* automatically compute drawing-space mouse coordinates */
this.mousePos = { x: 0, y: 0 };
this.onmousemove = null;
this.element.addEventListener('mousemove', e => {
const matrix = this.context.getTransform();
matrix.invertSelf();
const screenX = e.offsetX; const screenY = e.offsetY;
this.mousePos.x = matrix.a*screenX + matrix.b*screenY;
this.mousePos.y = matrix.c*screenX + matrix.d*screenY;
if (this.onmousemove) this.onmousemove(this.mousePos);
});
}
fillWindow() {
const width = window.innerWidth;
const height = window.innerHeight;
const scale = Math.max(width, height);
this.element.width = width; this.element.height = height;
this.context.scale(scale, scale);
this.draw();
}
draw() {
this.context.clearRect(0, 0, 1, 1);
if (this.ondraw) this.ondraw(this.context);
}
}
export default Canvas;
|