The HTMLCanvasElement.toDataURL()
method returns a data URI 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/jpg
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 URI.
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:
var canvas = document.getElementById('canvas');
var dataURL = canvas.toDataURL();
console.log(dataURL);
var fullQuality = canvas.toDataURL('image/jpeg', 1.0);
var mediumQuality = canvas.toDataURL('image/jpeg', 0.5);
var 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() {
var aImages = document.getElementsByClassName('grayscale'),
nImgsLen = aImages.length,
oCanvas = document.createElement('canvas'),
oCtx = oCanvas.getContext('2d');
for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) {
oColorImg = aImages[nImgId];
nWidth = oColorImg.offsetWidth;
nHeight = oColorImg.offsetHeight;
oCanvas.width = nWidth;
oCanvas.height = nHeight;
oCtx.drawImage(oColorImg, 0, 0);
oImgData = oCtx.getImageData(0, 0, nWidth, nHeight);
aPix = oImgData.data;
nPixLen = aPix.length;
for (nPixel = 0; nPixel < nPixLen; nPixel += 4) {
aPix[nPixel + 2] = aPix[nPixel + 1] = aPix[nPixel] = (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3;
}
oCtx.putImageData(oImgData, 0, 0);
oGrayImg = new Image();
oGrayImg.src = oCanvas.toDataURL();
oGrayImg.onmouseover = showColorImg;
oColorImg.onmouseout = showGrayImg;
oCtx.clearRect(0, 0, nWidth, nHeight);
oColorImg.style.display = "none";
oColorImg.parentNode.insertBefore(oGrayImg, oColorImg);
}
}