HTMLCanvasElement.toDataURL() 方法返回一個包含圖片展示的 data URI 。可以使用 type 參數其類型,默認為 PNG 格式。圖片的分辨率為96dpi。
- 如果畫布的高度或寬度是0,那么會返回字符串“
data:,”。 - 如果傳入的類型非“
image/png”,但是返回的值以“data:image/png”開頭,那么該傳入的類型是不支持的。 - Chrome支持“
image/webp”類型。
語法EDIT
canvas.toDataURL(type, encoderOptions);
參數
-
type可選 -
圖片格式,默認為
image/png -
encoderOptions可選 -
圖片質量。取值范圍為
0到1。如果指定圖片格式為image/jpeg 或image/webp。如果超出取值范圍,將會使用默認值0.92。其他參數會被忽略。
返回值
示例
有如下<canvas>元素
<canvas id="canvas" width="5" height="5"></canvas>
可以用這樣的方式獲取一個 data-URL
var canvas = document.getElementById("canvas"); var dataURL = canvas.toDataURL(); console.log(dataURL); // "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby // blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
設置jpegs圖片的質量
var fullQuality = canvas.toDataURL("image/jpeg", 1.0); // data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z" var mediumQuality = canvas.toDataURL("image/jpeg", 0.5); var lowQuality = canvas.toDataURL("image/jpeg", 0.1);
示例:動態更改圖片
可以使用鼠標事件來動態改變圖片(這個例子中改變圖片灰度)。
HTML
<img class="grayscale" src="myPicture.png" alt="Description of my picture" />
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);
}
}
