Matt Coady
Matt Coady

Reputation: 3856

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?

Upvotes: 4

Views: 1628

Answers (3)

Jake Thakur
Jake Thakur

Reputation: 166

For anyone wanting to take any subsection of an initial canvas and convert it to png, the following modification of the code of @robertc worked for me:

let canvas = document.getElementById("mycanvas");
let saveCanvas = document.createElement('canvas');
saveCanvas.width = 150; // width of saved image
saveCanvas.height = 100; // height of saved image
let cropStartX = 0; // position to start cropping image
let cropStartY = 0;
saveCanvas.getContext('2d').drawImage(canvas, cropStartX, cropStartY, saveCanvas.width, saveCanvas.height, 0, 0, saveCanvas.width, saveCanvas.height);
var img = new_canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237865

The way to do this would be to use another canvas element to get the area you want and then crop that.

var canvas      = document.getElementById('mycanvas'),
    smallcanvas = document.createElement('canvas'),
    imagedata   = '';

smallcanvas.getContext('2d').drawImage(canvas, 0, 0, null, null, 0, 0, 150, 100);
imagedata = smallcanvas.toDataURL();

Upvotes: 2

robertc
robertc

Reputation: 75707

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+'"/>');

Upvotes: 5

Related Questions