Created
January 28, 2022 10:01
-
-
Save audinue/a7bac663d531f7461fec9f6189f2862b to your computer and use it in GitHub Desktop.
Simple viewport panning and zooming without the use of matrix.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <canvas id="canvas" width="500" height="500" style="border: 1px solid"></canvas> | |
| <script> | |
| var panX = 0 | |
| var panY = 0 | |
| var zoom = 1 | |
| draw() | |
| function draw () { | |
| var ctx = canvas.getContext('2d') | |
| ctx.clearRect(0, 0, canvas.width, canvas.height) | |
| ctx.save() | |
| ctx.translate(panX, panY) | |
| ctx.scale(zoom, zoom) | |
| for (var y = 0; y < 10; y++) { | |
| for (var x = 0; x < 10; x++) { | |
| ctx.fillStyle = 'red' | |
| ctx.fillRect(x * 60, y * 60, 50, 50) | |
| } | |
| } | |
| ctx.restore() | |
| } | |
| // Pan the viewport on drag | |
| canvas.onmousedown = function (e) { | |
| e.preventDefault() | |
| canvas.onmouseup = function (e) { | |
| canvas.onmouseup = null | |
| canvas.onmousemove = null | |
| } | |
| canvas.onmousemove = function (e) { | |
| panX += e.movementX | |
| panY += e.movementY | |
| draw() | |
| } | |
| } | |
| // Zoom the viewport on mouse wheel | |
| canvas.onwheel = function (e) { | |
| var scale = e.wheelDelta < 0 ? 0.9 : 1.1 | |
| var x = e.offsetX | |
| var y = e.offsetY | |
| panX = panX * scale - (x * scale - x) | |
| panY = panY * scale - (y * scale - y) | |
| zoom = zoom * scale | |
| draw() | |
| } | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment