Skip to content Skip to sidebar Skip to footer

How Do I Effectively Calculate Zoom Scale?

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 same

Solution 1:

[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

Post a Comment for "How Do I Effectively Calculate Zoom Scale?"