Search code examples
javascripthtmlcanvas

Zooming scale function not working with HTML canvas


I have a canvas which takes up the entire webpage - it is has a top-left point at (0, 0), and a width and height equal to the browsers width and height. I made the following function to zoom into an (x, y) location (which are from event.x and event.y detecting a screen click). Here is my code:

// zooms the canvas by the zoom factor into the values given
function zoomCanvas(x, y, zoom) {
    // gets new canvas
    let newCanvas = document.getElementById("zoomed-canvas");
    let newCtx = newCanvas.getContext('2d');

    // gets old canvas
    let oldCanvas = document.getElementById("canvas");
    let oldCtx = oldCanvas.getContext('2d');

    // sets width and height
    newCanvas.width = width();
    newCanvas.height = height();

    // copies canvas
    newCtx.drawImage(oldCanvas, 0, 0);

    // clear old canvas
    oldCtx.clearRect(0, 0, width(), height());

    // gets scale factor
    let scale = 1 / (1 - zoom);
    let xx = Math.floor(x * (scale) - x);
    let yy = Math.floor(y * (scale) - y);
    console.log(scale, xx, yy);

    // zooms
    newCanvas.style.scale = `${scale}`;
    newCanvas.style.left = `-${xx}px`;
    newCanvas.style.top = `-${yy}px`;
}

Everything up to the "// zooms" part works as intended. When I try zooming in, the center of zoom is nowhere near where my mouse clicked. Since I can visibly see the zoom, I think the problem lies in the calculation of new coordinates. I have tried several different calculations but nothing seems to work.


Solution

  • I solved it. Using

    let xx = (x - (width() / 2)) * (scale - 1);
    let yy = (y - (height() / 2)) * (scale - 1);
    

    fixes the zoom.