How to save canvas as an image with canvas.toDataURL() and JavaScript?

Spread the love

Sometimes, we want to save canvas as an image with canvas.toDataURL() and JavaScript.

In this article, we’ll look at how to save canvas as an image with canvas.toDataURL() and JavaScript.

How to save canvas as an image with canvas.toDataURL() and JavaScript?

To save canvas as an image with canvas.toDataURL() and JavaScript, we set the URL returned by toDataURL as the href value.

For instance, we write

const image = canvas
  .toDataURL("image/png")
  .replace("image/png", "image/octet-stream");

window.location.href = image;

to call toDataURL with the MIME type of the image to save.

And then we replace that with "image/octet-stream".

Next, we set the returned URL as the value of window.location.href to save the image.

Conclusion

To save canvas as an image with canvas.toDataURL() and JavaScript, we set the URL returned by toDataURL as the href value.

Leave a Reply

Your email address will not be published. Required fields are marked *