diff options
Diffstat (limited to 'src/Canvas.js')
-rw-r--r-- | src/Canvas.js | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/src/Canvas.js b/src/Canvas.js new file mode 100644 index 0000000..590034a --- /dev/null +++ b/src/Canvas.js @@ -0,0 +1,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; |