[Recipe]: Save Canvas content to File on server
Save to File
If you have some logic with images, drawing or blurring in javascript, you might want to save image back to server. Here is how to use toBlob
function:
const canvas = document.getElementById("canvasID");
canvas.toBlob(bytes => {
// here is saving of actual image file content
save(bytes);
});
save
function should do something with it's argument, bytes buffer. For example, send back to server. Backend can simply put it into file with appropriate extension like *.jpg or *.png.
Base64 and Html rendering
The more common way is using toDataUrl
function like this:
const canvas = document.getElementById("canvasID");
const imgData = canvas.toDataUrl();
But returned result has format different from pure *,jpg or *.png file. It has string representation like this: data:image/png;base64,....
It an be used as image data in html for <img>
tag:
<img src="data:image/png;base64,....">
But saving it to file will lead to corrupted image. Decoding it from base64 doesn't give correct image as well.
Test your code and use functions which are appropriate for particular task!