Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert small part of a canvas to png

I turning my html5 canvas into a png using the following code:

var canvas = document.getElementById("mycanvas");
var img    = canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');

What do I add to this so it will only grab the top left 150x100 pixels, instead of the whole canvas?

like image 332
Matt Coady Avatar asked Feb 16 '23 07:02

Matt Coady


1 Answers

Create a second canvas of 150x100 pixels, grab the top left corner of the current canvas and paint it in with drawImage(), then call toDataURL() on the new canvas:

var canvas = document.getElementById("mycanvas");
var new_canvas = document.createElement('canvas');
new_canvas.width = 150;
new_canvas.height = 100;
new_canvas..getContext('2d').drawImage(canvas, 150, 100);
var img = new_canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');
like image 132
robertc Avatar answered Feb 28 '23 12:02

robertc