views:

32

answers:

1

How is it possible to zoom a photo contained in a <canvas> tag? In particular I'd like to zoom in on the photo at the point the user clicked.

The zoom is not difficult to do:

img.width = img.width + 100;
img.height = img.height + 100;
ctx.drawImage(img,0,0,img.width,img.height);

The problem is that I would also like to center the zoomed image in the point of the click, like a normal magnifier.

+2  A: 

[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);
galambalazs
Perfect thank you :)
Claudio