保存:把绘制在canvas上的图形另存到另一个页面中
下载:把绘制的图形下载到本地
<body>
<canvas id="myCanvas" width="300" height="300"></canvas>
<button id="save">保存</button>
<button id="dowloadImg">下载</button>
</body>
<script>
window.onload = function(){
draw();
var saveBtn = document.getElementById("save");
bindButtonEvent(saveBtn, "click", saveImgInfo);
var dowloadBtn = document.getElementById("dowloadImg");
bindButtonEvent(dowloadBtn, "click", dowloadImg);
}
function draw(){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(25,25,100,100);
ctx.fillStyle = "green";
ctx.fillRect(58,74,125,100);
ctx.fillStyle = "rgba(0,0,0,1)";
}
function bindButtonEvent(element, type, handler){//兼容新旧两种浏览器的事件绑定方式
if(element.addEventListener){
element.addEventListener(type, handler, false);
}else{
element.attachEvent("on"+type, handler);
}
}
function saveImgInfo(){
var canvas = document.getElementById("myCanvas");
var imgInfo = canvas.toDataURL("image/png"); //将画布转换为图片
var w = window.open("about:blank","image from canvas"); //新开空白页
w.document.write("<img src='"+imgInfo+"'alt='from canvas'/>"); //将保存的图片放上去
}
function dowloadImg(){
console.log(2);
var canvas = document.getElementById("myCanvas");
var imgInfo = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
window.location.href = imgInfo; //当前页下载
}
</script>