I'm following a code on https://www.geeksforgeeks.org/how-to-zoom-in-on-a-point-using-scale-and-translate/ where a user can Zoom in and out from an HTML 5 Canvas.
I want to add the functionality of Canvas Pan (so that I can move a number of objects easily).
The code below
<html>
<head/>
<body>
<center>
<canvas id="canvas" width="500" height="500"></canvas>
</center>
<script>
var zoomIntensity = 0.1;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = canvas.clientWidth;
var height = canvas.clientHeight;
var scale = 1;
var orgnx = 0;
var orgny = 0;
var visibleWidth = width;
var visibleHeight = height;
draw();
function draw() {
context.fillStyle = "white";
context.fillRect(orgnx, orgny, width / scale, height / scale);
context.fillStyle = "green";
context.fillRect(250,50,100,100);
}
canvas.onwheel = function(event) {
event.preventDefault();
var x = event.clientX - canvas.offsetLeft;
var y = event.clientY - canvas.offsetTop;
var scroll = event.deltaY < 0 ? 1 : -2;
var zoom = Math.exp(scroll * zoomIntensity);
context.translate(orgnx, orgny);
orgnx -= x / (scale * zoom) - x / scale;
orgny -= y / (scale * zoom) - y / scale;
context.scale(zoom, zoom);
context.translate(-orgnx, -orgny);
// Updating scale and visisble width and height
scale *= zoom;
visibleWidth = width / scale;
visibleHeight = height / scale;
draw();
}
</script>
</body>
</html>
I'm trying to change the orgnx and orgny to create pan effect, but its not working. Even when I call context.translate(orgnx, orgny);
to create Pan effect, it doesn't work well. How I can enable Canvas Pan effect without compromising the Zoom. I know I'm missing something here.
I was able to figure out the issue. In order to pan the canvas in the above code
context.translate(orgnx, orgny);
orgnx += distX * (1/scale);
orgny += distY * (1/scale);
context.translate(-orgnx, -orgny);
draw();
distX and distY are respective distances to pan the canvas