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

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

javascript - Crop an image displayed in a Canvas

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...