The HTMLCanvasElement.toDataURL()
method returns a data URL containing a representation of the image in the format specified by the type
parameter.
The desired file format and image quality may be specified. If the file format is not specified, or if the given format is not supported, then the data will be exported as image/png
. In other words, if the returned value starts with data:image/png
for any other requested type
, then that format is not supported.
Browsers are required to support image/png
; many will support additional formats including image/jpeg
and image/webp
.
The created image data will have a resolution of 96dpi for file formats that support encoding resolution metadata.
toDataURL()
toDataURL(type)
toDataURL(type, encoderOptions)
A string containing the requested data URL.
If the height or width of the canvas is 0
or larger than the maximum canvas size, the string "data:,"
is returned.
Given this <canvas>
element:
<canvas id="canvas" width="5" height="5"></canvas>
You can get a data-URL of the canvas with the following lines:
const canvas = document.getElementById("canvas");
const dataURL = canvas.toDataURL();
console.log(dataURL);
const fullQuality = canvas.toDataURL("image/jpeg", 1.0);
const mediumQuality = canvas.toDataURL("image/jpeg", 0.5);
const lowQuality = canvas.toDataURL("image/jpeg", 0.1);
You can use this technique in coordination with mouse events in order to dynamically change images (gray-scale vs. color in this example):
HTML
<img class="grayscale" src="myPicture.png" alt="Description of my picture" />
JavaScript
window.addEventListener("load", removeColors);
function showColorImg() {
this.style.display = "none";
this.nextSibling.style.display = "inline";
}
function showGrayImg() {
this.previousSibling.style.display = "inline";
this.style.display = "none";
}
function removeColors() {
const images = document.getElementsByClassName("grayscale");
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
for (const colorImg of images) {
const width = colorImg.offsetWidth;
const height = colorImg.offsetHeight;
canvas.width = width;
canvas.height = height;
ctx.drawImage(colorImg, 0, 0);
const imgData = ctx.getImageData(0, 0, width, height);
const pix = imgData.data;
const pixLen = pix.length;
for (let pixel = 0; pixel < pixLen; pixel += 4) {
pix[pixel + 2] =
pix[pixel + 1] =
pix[pixel] =
(pix[pixel] + pix[pixel + 1] + pix[pixel + 2]) / 3;
}
ctx.putImageData(imgData, 0, 0);
const grayImg = new Image();
grayImg.src = canvas.toDataURL();
grayImg.onmouseover = showColorImg;
colorImg.onmouseout = showGrayImg;
ctx.clearRect(0, 0, width, height);
colorImg.style.display = "none";
colorImg.parentNode.insertBefore(grayImg, colorImg);
}
}