Skip to content Skip to sidebar Skip to footer

How To Save An Html5 Canvas To A Png

I am trying to have a canvas be saved as an image so it can be put somewhere else on the website as an tag. I have seen approaches like this: var canvas = document.getElementById(

Solution 1:

For the frontside here's a full working example only showing a red background. http://jsfiddle.net/gramhwkg/

// create a canvas// If the canvas is already a dom element//var canvas = document.getElementById("canvas");// otherwise you'd rather dovar canvas = document.createElement('canvas');

// Then set a width/height grab its context.
canvas.width = 900;
canvas.height = 400;
var ctx = canvas.getContext("2d");

// ... And do plenty of nice stuff with it.// I'll just draw it Red.
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,900,400);

// When you want it to appear elsewhere.var data = canvas.toDataURL();
var picture = document.getElementById("my-picture");
picture.innerHTML = '<img src="' + data + '"/>' ;

The backend part is not much harder. Just POST to php the same image data variable and handle it that way :

$canvas = base64_decode(str_replace('data:image/png;base64,', '' , $value['picture']));
file_put_contents('my_custom_path/my_custom_filename.png', $canvas);

Hope this helps !

Post a Comment for "How To Save An Html5 Canvas To A Png"