如何基于鼠标点击来裁剪选定的矩形 [英] How to crop a selected rectangle using based on mouse clicks

查看:118
本文介绍了如何基于鼠标点击来裁剪选定的矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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



我该怎么做?

解决方案




  • 将图像绘制到画布上

      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;


  • 创建第二个canvas元素并将其大小设置为裁切尺寸:

      var secondCanvas = document.createElement('canvas'); 
    secondCanvas.width = width;
    secondCanvas.height = height;
    document.body.appendChile(secondCanvas);


  • 使用的剪辑版本drawImage 将第一个画布上的裁剪矩形绘制到第二个画布上

      secondCanvas.drawImage(canvas,
    x,y ,width,height,//从第一个画布中剪切裁剪矩形
    0,0,width,height //仅将裁剪后的部分绘制到第一个画布上
    );




现在用户所选的部分图片在第二个画布上。



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

  var img = new Image(); 
img.onload = start;
img.src = secondCanvas.toDataURL();
function start(){
//此时,img包含原始图像的裁剪部分
}


I have drawn an image on the canvas.

I want the user to click on the canvas to crop a portion of the image.

How can I do this?

解决方案

Here's an outline to get you started:

  • Draw the image onto the canvas

    var canvas=document.getElementById('myCanvas');
    canvas.drawImage(yourImageObject,0,0);
    

  • Listen for mousedown events.

    canvas.onmousedown=function(e){handleMouseDown(e);};
    

  • Have the user click in the top-left [x0,y0] and bottom-right [x1,y1] corners where they want to crop and record those 2 mouse positions.

  • The cropping rectangle is defined like this:

    var x=x0; 
    var y=y0;
    var width=x1-x0;
    var height=y1-y0;
    

  • Create a second canvas element and size it to the cropping size:

    var secondCanvas = document.createElement('canvas');
    secondCanvas.width = width;
    secondCanvas.height = height;
    document.body.appendChile(secondCanvas);
    

  • Use the clipping version of drawImage to draw the cropping rectangle from the first canvas onto the second canvas

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

The user's selected portion of the image is now on the second canvas.

If you want to convert the second canvas into an image object, you can do this:

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 
}

这篇关于如何基于鼠标点击来裁剪选定的矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆