Save HTML5 Canvas as image on server

Working with HTML we sometimes face with necessity of saving the results as image. The image can be saved on server or we can force downloading the result directly into your browser.

You may think it might be complex, but it is not in fact.

01 <canvas id="my-canvas" width="600" height="300"></canvas>
02 <script>
03     var canvas = document.getElementById('my-canvas');
04     var context = canvas.getContext('2d');
05     var x = 125, y = 100;
06     // begin custom shape
07     context.beginPath();
08     context.moveTo(x, y);
09     context.bezierCurveTo(x - 40, y + 20, x - 40, y + 70, x + 60, y + 70);
10     context.bezierCurveTo(x + 80, y + 100, x + 150, y + 100, x + 170, y + 70);
11     context.bezierCurveTo(x + 250, y + 70, x + 250, y + 40, x + 220, y + 20);
12     context.bezierCurveTo(x + 260, y - 40, x + 200, y - 50, x + 170, y - 30);
13     context.bezierCurveTo(x + 150, y - 75, x + 80, y - 60, x + 80, y - 30);
14     context.bezierCurveTo(x + 30, y - 75, x - 20, y - 60, x, y);
15     // complete custom shape
16     context.closePath();
17     context.lineWidth = 5;
18     context.fillStyle = '#8ED6FF';
19     context.fill();
20     context.strokeStyle = 'blue';
21     context.stroke();
22 </script>

In this example, we use bezier curves to draw a simple cloud.

2. Next step is to convertthe  canvas image to base64:

1 var canvasData = canvas.toDataURL("image/png");

3. Finally, we can send the result base64 to server

1 $.ajax({
2     type: "POST",
3     url: "upload-image.php",
4     data: {
5         imgBase64: canvasData
6     }
7 }).done(function(o) {
8     console.log('uploaded');
9 });

4. Or alternatively, you can force the download into your browser:

1 const downloadLink = document.createElement('a');
2 document.body.appendChild(downloadLink);
3 downloadLink.href = canvasData;
4 downloadLink.target = '_self';
5 downloadLink.download = 'image.png';
6 downloadLink.click();

5. If you wish to save the image on your server, it can be done in any language, below you can find a basic example in PHP:

1 if (isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
2     $imageData $GLOBALS['HTTP_RAW_POST_DATA'];
3     $filteredData substr($imageDatastrpos($imageData',') + 1);
4     $unencodedData base64_decode($filteredData);
5     $fp fopen('/path/to/file.png''wb');
6     fwrite($fp$unencodedData);
7     fclose($fp);
8 }

Thanks for your attention to this lesson