How to crop a selected rectangle using based on mouse clicks

て烟熏妆下的殇ゞ 提交于 2020-01-06 04:00:15

问题


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?


回答1:


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 
}


来源:https://stackoverflow.com/questions/38568032/how-to-crop-a-selected-rectangle-using-based-on-mouse-clicks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!