简体   繁体   中英

HTML5 Canvas ~ Zoom and Keep Current Canvas Relative Offset (view port center point)

The post on, Zoom in on a point (using scale and translate)
did not quite provide the answer I was looking for; which is, "How to you keep the current point on the canvas that is centered in the view port window at the same relative position after you scale the canvas?"

canvas offset

The blue rectangle above represents the view port (monitor).

The red rectangle represents the canvas which currently extends beyond the view port.

When you scale the canvas how do you keep the red dot at the same relative position?

Let's just look at the x dimension:

The current width of the canvas is 100 = 30 + 50 + 20

If we scale by 2x the current width becomes 200 = 60 + 100 + 40; however, the view port only represents 50 of the new 100 width: 200 = 60 + (25 + 50 + 25) + 40

The numbers you really care about are the x and y offsets which position the canvas; currently the x offset is -30. The new offset, to keep the red dot at the same relative position after a 2x scale will be -85 = (-1)*(60 + 25).

The new relative position will be 110 = 60 + 25 + 25 (the second 25 is half the view port dimension). Note that 55 x 2 = 110.

In code:

    boundingBoxLeft = boundingBox.left;
    beginCanvasWidth = canvas.width;
    canvas.width = canvasWidth*scaleFactor;
    var scaleChange = canvas.width/beginCanvasWidth;

    var leftOffset = ((-1)*boundingBoxLeft*scaleChange) + 
            (((window.innerWidth*scaleChange) - window.innerWidth)/2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM