Crop an image displayed in a Canvas
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
Create a new canvas at destination size, draw in the cropped image using drawImage() and insert that canvas into the DOM avoiding using img and data-uri:
var ccanvas = document.createElement("canvas"),
cctx = ccanvas.getContext("2d");
ccanvas.width = w;
ccanvas.height = h;
// draw with crop arguments
cctx.drawImage(image_src, x, y, w, h, 0, 0, w, h);
// ^^^^^^^^^^ source region
// ^^^^^^^^^^ dest. region
// insert cropped image somewhere in the DOM tree:
document.body.appendChild(ccanvas);
window.onload = function() {
var img = document.getElementById("image_src");
document.body.appendChild(region2canvas(img, 150, 60, 220, 200));
}
function region2canvas(img, x, y, w, h) {
var ccanvas = document.createElement("canvas"),
cctx = ccanvas.getContext("2d");
ccanvas.width = w;
ccanvas.height = h;
// draw with crop arguments
cctx.drawImage(img, x, y, w, h, 0, 0, w, h);
return ccanvas;
}
<img src="http://i.imgur.com/kWI4Cmz.png" id="image_src">
The key to cropping from one image is that the context's drawImage method allows us to render a cropped section of the source image to the canvas.
context.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh);
img - Source image object
sx - Source x
sy - Source y
sw - Source width
sh - Source height
dx - Destination x
dy - Destination y
dw - Destination width
dh - Destination height