Upload a canvas image throug ajax

Posted by Vasilis on October 11, 2019

I wanted to save a screenshot from the game I build so players can see the last moment before the end game. The games uses html5 canvas, so the idea was to upload the canvas and save it as png image in server.

We can send the image to server as a base64 encoded:

var dataURL = canvas.toDataURL();
$.ajax({
  type: "POST",
  url: "/saveBase64",
  data: { imgBase64: dataURL }
})

The above ajax call is done with jQuery but you can use any other library. In the server side we create this endpoint:

$fileName = "screenshot.png";
$img = $_POST['data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
file_put_contents($fileName, $fileData);

 

Sources:

https://stackoverflow.com/questions/13198131/how-to-save-an-html5-canvas-as-an-image-on-a-server
https://stackoverflow.com/questions/1532993/i-have-a-base64-encoded-png-how-do-i-write-the-image-to-a-file-in-php