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

 2022-10-24    419  

有的朋友可能对于“借助toDataURL实现将HTML5 Canvas的内容保存为图片”还有很多不明白的地方,下面由77ISP云服务器技术小编为大家讲解一下,下面我们来一起看看吧!

将HTML5 Canvas的内容保存为图片主要思想是借助Canvas自己的API – toDataURL()来实现,具体实现如下,感兴趣的朋友可以参考下哈,希望对你有所帮助
主要思想是借助Canvas自己的API – toDataURL()来实现,整个实现
HTML + 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("借助toDataURL实现将HTML5"); 
} 
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 
} 
 
 
 

运行效果如下

以上就是“借助toDataURL实现将HTML5 Canvas的内容保存为图片”的详细内容,更多请关注77isp云服务器技术网其它相关文章!

原文链接:https://77isp.com/post/3951.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。