I try to copy a certain part of a canvas, then write the copied part in an image. Here is my (wrong) approach:
var c = document.getElementById('MyCanvas'),
ctx = c.getContext('2d');
var ImageData = ctx.getImageData( 25, 25, 150, 150 );
var MyImage = new Image();
MyImage.src = ImageData ; // <-- This is wrong, but I mean something like this
Do you know how can I do it? Thank you in advance.
ps: I don't want to copy the whole canvas, but a certain part of it.
You could accomplish that in the following way ...
var c = document.getElementById('MyCanvas');
var ctx = c.getContext('2d');
// draw rectangle
ctx.fillRect(0, 0, 200, 200);
ctx.fillStyle = '#07C';
ctx.fillRect(25, 25, 150, 150);
// get image data
var ImageData = ctx.getImageData(25, 25, 150, 150);
// create image element
var MyImage = new Image();
MyImage.src = getImageURL(ImageData, 150, 150);
// append image element to body
document.body.appendChild(MyImage);
function getImageURL(imgData, width, height) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
ctx.putImageData(imgData, 0, 0);
return canvas.toDataURL(); //image URL
}
<canvas id="MyCanvas" width="200" height="200"></canvas>
apology for not giving explanation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With