簡體   English   中英

單擊時調整畫布圖像的大小,並使用javascript將其居中

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

如何縮放<canvas>標簽中包含的照片? 特別是,我想在用戶單擊時放大照片。

縮放並不難:

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

問題是,我也想像普通放大鏡一樣將縮放后的圖像定位在點擊位置上。

[ 工作演示 ]

數據

  • 調整大小: R
  • 帆布尺寸: CwCh
  • 調整圖像大小: IwIh
  • 調整圖像大小: IxIy
  • 單擊畫布上的位置: PcxPcy
  • 單擊原始圖像上的位置: PoxPoy
  • 單擊調整大小后的圖像上的位置: PrxPry

方法

  1. 單擊事件在畫布上的位置->在圖像上的位置: Pox = Pcx - IxPoy = Pcy - Iy
  2. 在圖像上的位置->在調整大小的圖像上的位置: Prx = Pox * RPry = Poy * R
  3. top = (Ch / 2) - Pryleft = (Cw / 2) - Prx
  4. ctx.drawImage(img, left, top, img.width, img.height)

履行

// 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