DEV Community

Cover image for How to Convert Canvas to an Image using JavaScript
Vishnu Damwala
Vishnu Damwala

Posted on • Originally published at meshworld.in

5 1

How to Convert Canvas to an Image using JavaScript

The HTMLCanvasElement has special method toDataURL() which returns a encoded data URI representing the image in the specified format(defaults to PNG).

  • If the canvas height or width is 0 or larger than the canvas maximum size, then the string containing "data:" is returned.
  • If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
  • Chrome also supports the WEBP(image/webp) type.

Syntax:

canvas.toDataURL(type, encoderOptions);

Parameters:

type (optional)
  • It indicates the type of image format.
  • It will have the value of string type and is an optional parameter with default format type value image/png.
encoderOptions (optional)
  • It indicates the type of image format.
  • It will have the value of number type and is an optional parameter with default value 0.92.
  • The value ranges from 0 to 1 indicating the quality of an image to use for formats that use lossy compression such as image/jpeg and image/webp.
  • Invalid value is ignored and default value is considered instead of it.

Return value

It returns a DOMString containing the requested data URI.

Example 1

<canvas id="canvas" width="640" height="360"></canvas>
var canvas = document.getElementById('canvas');
var dataURL = canvas.toDataURL();
console.log(dataURL);
/*
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABa...5i/JyZmJr6v77XLtUjciSUnklJd29flKi1cAPKgw"
*/

For more examples visit : How to Convert Canvas to an Image using JavaScript

Hope you learn something new. If this article was helpful, share it.

Happy coding

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs