Javascript 如何基于鼠标单击裁剪选定的矩形

Javascript 如何基于鼠标单击裁剪选定的矩形,javascript,html,canvas,Javascript,Html,Canvas,我在画布上画了一幅图 我希望用户点击画布来裁剪图像的一部分 我怎样才能做到这一点呢?这里有一个提纲让你开始: 将图像绘制到画布上 var canvas=document.getElementById('myCanvas'); canvas.drawImage(yourImageObject,0,0); 监听mousedown事件 canvas.onmousedown=function(e){handleMouseDown(e);}; 让用户点击左上角[x0,y0]和右下角[x1,y1]

我在画布上画了一幅图

我希望用户点击画布来裁剪图像的一部分


我怎样才能做到这一点呢?

这里有一个提纲让你开始:

  • 将图像绘制到画布上

    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 
}

这里有一个提纲让你开始:

  • 将图像绘制到画布上

    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 
}

你的问题是什么还不清楚。请试着更详细地描述你的问题。特别是第一句话很难理解,你是不是想裁剪一幅图像?您在画布中有一个图像,然后您希望用户在画布中定义一个矩形区域,裁剪画布,然后上载该图像?下面的链接显示了如何使用画布进行图像裁剪:不清楚您的问题是什么。请试着更详细地描述你的问题。特别是第一句话很难理解,你是不是想裁剪一幅图像?您在画布中有一个图像,然后您希望用户在画布中定义一个矩形区域,裁剪画布,然后上载该图像?以下链接显示了如何使用画布进行图像裁剪: