问题
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
mousedownevents.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
drawImageto draw the cropping rectangle from the first canvas onto the second canvassecondCanvas.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