简体   繁体   English

单击时调整画布图像的大小,并使用javascript将其居中

[英]Resize a canvas image on click and center that with javascript

How is it possible to zoom a photo contained in a <canvas> tag? 如何缩放<canvas>标签中包含的照片? 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. 问题是,我也想像普通放大镜一样将缩放后的图像定位在点击位置上。

[ Working demo ] [ 工作演示 ]

Data 数据

  • Resize by: R 调整大小: R
  • Canvas size: Cw , Ch 帆布尺寸: CwCh
  • Resized image size: Iw , Ih 调整图像大小: IwIh
  • Resized image position: Ix , Iy 调整图像大小: IxIy
  • Click position on canvas: Pcx , Pcy 单击画布上的位置: PcxPcy
  • Click position on original image: Pox , Poy 单击原始图像上的位置: PoxPoy
  • Click position on resized image: Prx , Pry 单击调整大小后的图像上的位置: PrxPry

Method 方法

  1. Click event position on canvas -> position on image: Pox = Pcx - Ix , Poy = Pcy - Iy 单击事件在画布上的位置->在图像上的位置: Pox = Pcx - IxPoy = Pcy - Iy
  2. Position on image -> Pos on resized image: Prx = Pox * R , Pry = Poy * R 在图像上的位置->在调整大小的图像上的位置: Prx = Pox * RPry = Poy * R
  3. top = (Ch / 2) - Pry , left = (Cw / 2) - Prx top = (Ch / 2) - Pryleft = (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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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