Reputation: 2244
I have a canvas
with an id
of cnv
.
<canvas id='cnv'></canvas>
The dark rectangle is the whole canvas. I want to create another canvas that contains only the white region in the old canvas. How will I transfer a part of a canvas to a new canvas?
var cnv = document.getElementById('cnv');
I don't know what to do next in my code above.
Upvotes: 0
Views: 36
Reputation:
Assuming you have the region specificed in x, y, width and height, you can do:
function regionToCanvas(canvas, x, y, w, h) {
var c = document.createElement("canvas"), // create new canvas
ctx = c.getContext("2d"); // context for new canvas
c.width = w; // set size = w/h
c.height = h;
ctx.drawImage(canvas, x, y, w, h, 0, 0, w, h); // draw in region at (0,0)
return c; // return canvas
}
Then call, example:
var newCanvas = regionToCanvas(cnv, x, y, width, height);
document.body.appendChild(newCanvas); // add to DOM
Upvotes: 1