0

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("canvas");
var context = canvas.getContext("2d");
var strDataURI = canvas.toDataURL("image/png;base64");
document.write('<img src="'+strDataURI+'"/>');

But I am not sure how to implement it. I also would like a copy of the image to be saved as an actual file on the server as well but I am not sure where to start.

When I implement the above code, I put it at the bottom of my canvas script like such:

var finish = document.getElementID('finish');
finish.onclick = function() {

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var strDataURI = canvas.toDataURL("image/png;base64");
};

But I don't know how to actually reference the image. A little help for noob is all I need.

Zach10za
  • 100
  • 8
  • He wants the user to download the file. I want to just display it and download it to the server. @JeremyJStarcher – Zach10za Aug 09 '14 at 06:42

1 Answers1

0

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 do
var 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 !

Julien Garcia
  • 123
  • 1
  • 9