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