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
Data
R
Cw
, Ch
Iw
, Ih
Ix
, Iy
Pcx
, Pcy
Pox
, Poy
Prx
, Pry
Method
Pox = Pcx - Ix
, Poy = Pcy - Iy
Prx = Pox * R
, Pry = Poy * R
top = (Ch / 2) - Pry
, left = (Cw / 2) - Prx
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