Skip to content

Instantly share code, notes, and snippets.

@audinue
Created January 28, 2022 10:01
Show Gist options
  • Select an option

  • Save audinue/a7bac663d531f7461fec9f6189f2862b to your computer and use it in GitHub Desktop.

Select an option

Save audinue/a7bac663d531f7461fec9f6189f2862b to your computer and use it in GitHub Desktop.
Simple viewport panning and zooming without the use of matrix.
<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