有时候,我们绘制好的canvas想存储为本地图片,该怎么做呢?canvas提供了一个重要的方法toDataURL(),这个方法能把画布里的图案转变成base64编码格式的png或者其他格式的图片(根据你传入的mine类型的参数),然后返回 Data URL数据。接下来我们看具体是怎么实现的。
html页面一个canvas画布:
代码语言:javascript复制<canvas width=200 height=200 id="thecanvas"></canvas>
<button id="saveImageBtn">Save Image</button>
<button id="downloadImageBtn">Download Image</button>
对应的js代码实现:
代码语言:javascript复制window.onload = function() {
draw();
var saveButton = document.getElementById("saveImageBtn");
bindButtonEvent(saveButton, "click", saveImageInfo);
var dlButton = document.getElementById("downloadImageBtn");
bindButtonEvent(dlButton, "click", saveAsLocalImage);
};
function draw(){
var canvas = document.getElementById("thecanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
ctx.fillRect(25,25,100,100);
ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
ctx.fillRect(58, 74, 125, 100);
ctx.fillStyle = "rgba( 0, 0, 0, 1)"; // black color
ctx.fillText("Gloomyfish - Demo", 50, 50);
}
function bindButtonEvent(element, type, handler)
{
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on' type, handler);
}
}
function saveImageInfo ()
{
var mycanvas = document.getElementById("thecanvas");
var image = mycanvas.toDataURL("image/png");
var w=window.open('about:blank','image from canvas');
w.document.write("<img src='" image "' alt='from canvas'/>");
}
function saveAsLocalImage () {
var myCanvas = document.getElementById("thecanvas");
// here is the most important part because if you dont replace you will get a DOM 18 exception.
// var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png");
var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
window.location.href=image; // it will save locally
}
点击save按钮后,显示图片,点击图片即可弹出下载对话框。