Navigate back to the homepage

How to Convert Canvas to an Image using JavaScript

Vishnu Damwala
May 11th, 2020 · 1 min read

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:

1canvas.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

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

Examples

1<canvas id="canvas" width="640" height="360"></canvas>
1function convertCanvasToImage() {
2 let canvas = document.getElementById("canvas");
3 let image = new Image();
4 image.src = canvas.toDataURL();
5 return image;
6}
7
8let pnGImage = convertCanvasToImage();
9document.appendChild(pnGImage);

This code will append image element into your browser document.

Different image quality with jpegs format type

1var highQuality = canvas.toDataURL("image/jpeg", 1.0);
2// "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQ...DVLFP+UpPr5fYpqp1BAEAQBAEB//Z"
3var mediumQuality = canvas.toDataURL("image/jpeg", 0.5);
4var lowQuality = canvas.toDataURL("image/jpeg", 0.1);

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

Happy coding

More articles from MeshWorld

How to open a Command Menu in Chromium based browsers such as Google Chrome

A guide on how to open the Command Menu, run commands, see other actions, and more.

May 6th, 2020 · 1 min read

Program for Collatz Conjecture in JavaScript

The Collatz Conjecture also known as 3n + 1 conjecture is an eventually one of the unsolved problem in mathematics

May 3rd, 2020 · 1 min read
© 2017–2020 MeshWorld
Link to $https://twitter.com/meshworldindiaLink to $https://facebook.com/meshworldindiaLink to $https://instagram.com/meshworld.india/