Upload a canvas image throug ajax

July 28, 2020

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();
  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);