借助toDataURL实现将HTML5 Canvas的内容保存为图片

发布时间:2022-05-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了借助toDataURL实现将HTML5 Canvas的内容保存为图片脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
HTML5 canvas的内容保存为图片主要思想是借助Canvas自己的API - toDataURL()来实现,具体实现如下,感兴趣的朋友可以参考下哈,希望对你有所帮助 主要思想是借助Canvas自己的API - toDataURL()来实现,整个实现
HTML + JavaScript的代码很简单

<html> 
<;meta http-equiv="X-UA-Compatible" content="chrome=1"> 
<head> 
<script> 
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(&#39;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 
} 
</script> 
</head> 
<body bgcolor="#E6E6FA"> 
<p> 
<canvas width=200 height=200 id="thecanvas"></canvas> 
<button id="saveImageBtn">Save Image</button> 
<button id="downloadImageBtn">Download Image</button> 
</p> 
</body> 
</html>

运行效果如下

@H_126_9@

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于HTML5 Canvas的事件处理

AngularJS结合canvas画图的实现

以上就是借助toDataURL实现将HTML5 Canvas的内容保存为图片的详细内容,更多请关注脚本宝典其它相关文章

脚本宝典总结

以上是脚本宝典为你收集整理的借助toDataURL实现将HTML5 Canvas的内容保存为图片全部内容,希望文章能够帮你解决借助toDataURL实现将HTML5 Canvas的内容保存为图片所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:图片"