【问题标题】:Resize a canvas image on click and center that with javascript单击时调整画布图像的大小并使用 javascript 将其居中
【发布时间】:2011-04-23 12:26:54
【问题描述】:

如何缩放包含在<canvas> 标签中的照片? 特别是我想在用户点击的地方放大照片。

缩放并不难:

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

问题是我还想将缩放后的图像放在点击点的中心,就像普通的放大镜一样。

【问题讨论】:

    标签: javascript image canvas resize


    【解决方案1】:

    [Working demo]

    数据

    • 调整大小:R
    • 画布尺寸:CwCh
    • 调整后的图像大小:IwIh
    • 调整大小的图像位置:IxIy
    • 在画布上的点击位置:Pcx, Pcy
    • 原图点击位置:Pox,Poy
    • 在调整大小的图像上单击位置:PrxPry

    方法

    1. 点击事件在画布上的位置 -> 图像上的位置:Pox = Pcx - Ix, Poy = Pcy - Iy
    2. 图像上的位置 -> 调整大小图像上的位置: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)

    实施

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

    【讨论】:

      猜你喜欢
      • 2014-05-07
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 2013-10-06
      • 2020-01-21
      相关资源
      最近更新 更多