Home > Article > Web Front-end > How to Save a Canvas as an Image in HTML5?
Saving Canvas as Image using Canvas.toDataURL()
In HTML5, you can create and manipulate images on a canvas element. To save the canvas as an image, you can use the canvas.toDataURL() method. This method returns a base64-encoded string representation of the canvas content in the specified image format.
However, you may encounter issues if you attempt to save the canvas as an image using the following code:
function putImage() { var canvas1 = document.getElementById("canvasSignature"); if (canvas1.getContext) { var ctx = canvas1.getContext("2d"); var myImage = canvas1.toDataURL("image/png"); } var imageElement = document.getElementById("MyPix"); imageElement.src = myImage; }
This code fails because it does not properly handle the base64-encoded string. To save the canvas as an image, you need to use the following enhanced code:
var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); window.location.href = image;
Here, the replace() method is used to convert the base64-encoded string to an octet-stream, which is compatible with the window.location.href assignment. This code will now successfully save the canvas as an image locally.
The above is the detailed content of How to Save a Canvas as an Image in HTML5?. For more information, please follow other related articles on the PHP Chinese website!