Is there a way to zoom on the cursor point using this code? I can't get my head around to doing it. The canvas zooms but it only zooms in and out from the top left corner.
var previousMousePosition = new Vector(0, 0);
function OnMouseWheel (event) {
var delta = event.wheelDelta ? event.wheelDelta/40 : event.detail ? -event.detail : 0;
var mousePosition = new Vector(event.clientX, event.clientY);
var scaleFactor = 1.1;
if (delta) {
var factor = Math.pow(scaleFactor,delta);
context.scale(factor,factor);
}
}
The canvas always scales from it current origin. The default origin is [0,0].
If you want to scale from another point, you can first do
context.translate(desiredX,desiredY);
. This will reset the origin of the canvas to [desiredX,desiredY].That way your
context.scale
will scale from your specified origin.Since all context transformations remain in effect for every subsequent drawing, you often want to reverse the transformations after you are done with the current drawing (=='resetting' for the next drawing which might/might not use the current transformations). To untransform, just call the transformation with negative arguments: eg.
context.scale(-factor,-factor)
. Transformations should be done in reverse order from their original transformations.So your refactored code could be: