I have a canvas tag:
I want to add a crop functionality, so I
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