【问题标题】:How to crop a selected rectangle using based on mouse clicks如何根据鼠标点击裁剪选定的矩形
【发布时间】:2016-07-26 03:05:49
【问题描述】:

我在画布上绘制了一张图片。

我希望用户单击画布以裁剪图像的一部分。

我该怎么做?

【问题讨论】:

  • 很不清楚你的问题是什么。请尝试更详细地描述您的问题。尤其是第一句话很难理解。
  • 您要裁剪图像吗?您在画布中有一张图像,然后您希望用户在画布中定义一个矩形区域,裁剪画布,然后上传该图像?以下链接显示了如何使用画布进行图像裁剪:tympanus.net/codrops/2014/10/30/resizing-cropping-images-canvas

标签: javascript html canvas


【解决方案1】:

以下是帮助您入门的大纲:

  • 将图像绘制到画布上

    var canvas=document.getElementById('myCanvas');
    canvas.drawImage(yourImageObject,0,0);
    
  • 监听mousedown 事件。

    canvas.onmousedown=function(e){handleMouseDown(e);};
    
  • 让用户在左上角的[x0,y0] 和右下角的[x1,y1] 上单击他们想要裁剪并记录这两个鼠标位置的角落。

  • 裁剪矩形的定义如下:

    var x=x0; 
    var y=y0;
    var width=x1-x0;
    var height=y1-y0;
    
  • 创建第二个画布元素并将其调整为裁剪大小:

    var secondCanvas = document.createElement('canvas');
    secondCanvas.width = width;
    secondCanvas.height = height;
    document.body.appendChile(secondCanvas);
    
  • 使用drawImage 的裁剪版本将裁剪矩形从第一个画布绘制到第二个画布上

    secondCanvas.drawImage(canvas,
        x,y,width,height,  // clip just the cropping rectangle from the first canvas
        0,0,width,height   // draw just the cropped part onto the first canvas
    );
    

用户选择的图像部分现在位于第二个画布上。

如果要将第二个画布转换为图像对象,可以这样做:

var img=new Image();
img.onload=start;
img.src=secondCanvas.toDataURL();
function start(){
    // at this point, img contains the cropped portion of the original image 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-12
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多