Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a part of canvas to image

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.

like image 837
user3815508 Avatar asked Oct 28 '25 07:10

user3815508


1 Answers

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

like image 64
ɢʀᴜɴᴛ Avatar answered Oct 31 '25 13:10

ɢʀᴜɴᴛ