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;