Save HTML5 Canvas as image on server

Save HTML5 Canvas as image on server

0 16705

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.

<canvas id="my-canvas" width="600" height="300"></canvas>
<script>
    var canvas = document.getElementById('my-canvas');
    var context = canvas.getContext('2d');
    var x = 125, y = 100;
    // begin custom shape
    context.beginPath();
    context.moveTo(x, y);
    context.bezierCurveTo(x - 40, y + 20, x - 40, y + 70, x + 60, y + 70);
    context.bezierCurveTo(x + 80, y + 100, x + 150, y + 100, x + 170, y + 70);
    context.bezierCurveTo(x + 250, y + 70, x + 250, y + 40, x + 220, y + 20);
    context.bezierCurveTo(x + 260, y - 40, x + 200, y - 50, x + 170, y - 30);
    context.bezierCurveTo(x + 150, y - 75, x + 80, y - 60, x + 80, y - 30);
    context.bezierCurveTo(x + 30, y - 75, x - 20, y - 60, x, y);
    // complete custom shape
    context.closePath();
    context.lineWidth = 5;
    context.fillStyle = '#8ED6FF';
    context.fill();
    context.strokeStyle = 'blue';
    context.stroke();
</script>

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

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

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

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

$.ajax({
    type: "POST",
    url: "upload-image.php",
    data: {
        imgBase64: canvasData
    }
}).done(function(o) {
    console.log('uploaded');
});

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

const downloadLink = document.createElement('a');
document.body.appendChild(downloadLink);
downloadLink.href = canvasData;
downloadLink.target = '_self';
downloadLink.download = 'image.png';
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:

if (isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
    $imageData = $GLOBALS['HTTP_RAW_POST_DATA'];
    $filteredData = substr($imageData, strpos($imageData, ',') + 1);
    $unencodedData = base64_decode($filteredData);
    $fp = fopen('/path/to/file.png', 'wb');
    fwrite($fp, $unencodedData);
    fclose($fp);
}

Thanks for your attention to this lesson

SIMILAR ARTICLES


NO COMMENTS

Leave a Reply