Categories
JavaScript Answers

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

Spread the love

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

For instance, we write

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

to call toDataURL to return a base64 URL with the canvas content.

Then we call replace to replace 'image/png' with "image/octet-stream".

And then we set image as the value of window.location.href to save the image.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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