Thanks to the Zoom/scale at mouse position question, I implement my zoom/scale canvas. However when handling zooming in and out, this code was used:
offset.x = e.offsetX - (e.offsetX - offset.x) * step;
offset.y = e.offsetY - (e.offsetY - offset.y) * step;
I guess this code is to prevent the content under the mouse from moving away from the mouse area during zooming, but I don’t understand why it is implemented this way.
In other words, if I had to write it myself, I think I would get stuck here. I want to understand and master it, but it seems very difficult.
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
const step = 1.02;
const maxScale = 8;
const minScale = 0.3;
let isdragging = false,
scale = 1,
offset = {
x: 0,
y: 0
};
const drawCanvas = () => {
ctx.setTransform([1, 0, 0, 1, 0, 0]);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.setTransform(scale, 0, 0, scale, offset.x, offset.y);
ctx.fillStyle = "#000";
ctx.fillRect(0, 10, 20, 30);
ctx.fillRect(100, 100, 20, 30);
};
requestAnimationFrame(drawCanvas);
canvas.addEventListener("mousedown", function(e) {
isdragging = true;
});
canvas.addEventListener("mouseup", function() {
isdragging = false;
});
canvas.addEventListener("mousemove", function(e) {
if (isdragging) {
offset.x += e.movementX;
offset.y += e.movementY;
requestAnimationFrame(drawCanvas);
}
});
canvas.addEventListener("wheel", function(e) {
e.preventDefault();
if (e.deltaY <= 0) {
if ((scale * step) >= maxScale) {
return
}
scale *= step;
offset.x = e.offsetX - (e.offsetX - offset.x) * step; // why?
offset.y = e.offsetY - (e.offsetY - offset.y) * step; // why?
} else {
if ((scale / step) <= minScale) {
return
}
scale /= step;
offset.x = e.offsetX - (e.offsetX - offset.x) / step; // why?
offset.y = e.offsetY - (e.offsetY - offset.y) / step; // why?
}
requestAnimationFrame(drawCanvas);
}, {
passive: false
});
const btn = document.querySelector("button");
btn.addEventListener("click", function() {
scale *= step
drawCanvas();
});
* {
margin: 0;
padding: 0;
}
#canvas {
background-color: lightblue;
}
<canvas id="canvas" width="500" height="500"></canvas>
<button>scale * step</button>
1