Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a canvas tag:

<canvas width="321" height="240" id="img_source"></canvas>

I want to add a crop functionality, so I made a resizeable div that can identify the borders of cropped image through dragging the corners of the div using the mouse. It looks like the image below:

enter image description here

enter image description here

I'm currently using "toDataURL()" to convert the data from the canvass to an image that can be displayed by an <img> tag. My question is, How will I convert to an image only part of the canvas that was identified by the resizeable div?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
487 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use the method getImageData with the selected rectangle coordinates. For example:

let imageData = ctx.getImageData(65, 60, 100, 100);

Then create a secondary canvas with the desired sizes and use putImageData to set the pixels:

let canvas1 = document.createElement("canvas");
canvas1.width = 100;
canvas1.height = 100;
let ctx1 = canvas1.getContext("2d");
ctx1.rect(0, 0, 100, 100);
ctx1.fillStyle = 'white';
ctx1.fill();
ctx1.putImageData(imageData, 0, 0);

Finally use toDataURL to update the image:

dstImg.src = canvas1.toDataURL("image/png");

See the full sample I've prepared for you in CodePen


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...