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 > |
03 |
var canvas = document.getElementById('my-canvas'); |
04 |
var context = canvas.getContext('2d'); |
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 |
17 |
context.lineWidth = 5; |
18 |
context.fillStyle = '#8ED6FF'; |
20 |
context.strokeStyle = 'blue'; |
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
3 |
url: "upload-image.php" , |
8 |
console.log( 'uploaded' ); |
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' ; |
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 ( $imageData , strpos ( $imageData , ',' ) + 1); |
4 |
$unencodedData = base64_decode ( $filteredData ); |
5 |
$fp = fopen ( '/path/to/file.png' , 'wb' ); |
6 |
fwrite( $fp , $unencodedData ); |
Thanks for your attention to this lesson