How do I effectively calculate zoom scale?

前端 未结 1 723
鱼传尺愫
鱼传尺愫 2021-02-04 21:08

I have a draggeable image contained within a box. You can zoom in and zoom out on the image in the box which will make the image larger or smaller but the box size remains the s

相关标签:
1条回答
  • 2021-02-04 21:43

    [Working demo]

    Data

    • Resize by: R
    • Canvas size: Cw, Ch
    • Resized image size: Iw, Ih
    • Resized image position: Ix, Iy
    • Click position on canvas: Pcx, Pcy
    • Click position on original image: Pox, Poy
    • Click position on resized image: Prx, Pry

    Method

    1. Click event position on canvas -> position on image: Pox = Pcx - Ix, Poy = Pcy - Iy
    2. Position on image -> Pos on resized image: Prx = Pox * R, Pry = Poy * R
    3. top = (Ch / 2) - Pry, left = (Cw / 2) - Prx
    4. ctx.drawImage(img, left, top, img.width, img.height)

    Implementation

    // resize image
    I.w *= R;
    I.h *= R;
    
    // canvas pos -> image pos
    Po.x = Pc.x - I.left;
    Po.y = Pc.y - I.top;
    
    // old img pos -> resized img pos
    Pr.x = Po.x * R;
    Pr.y = Po.y * R;
    
    // center the point
    I.left = (C.w / 2) - Pr.x;
    I.top  = (C.h / 2) - Pr.y;
    
    // draw image
    ctx.drawImage(img, I.left, I.top, I.w, I.h);
    

    This is a general formula that works for zooming in or out, and can handle any point as the new center. To make it specific to your problem:

    • Pcx = Cw / 2, Pcy = Ch / 2 (alway use the center)
    • R < 1 for zooming out, and R > 1 for zooming in
    0 讨论(0)
提交回复
热议问题