首頁  >  文章  >  web前端  >  使用toDataURL實作將HTML5 Canvas的內容儲存為圖片

使用toDataURL實作將HTML5 Canvas的內容儲存為圖片

不言
不言原創
2018-06-22 14:33:032132瀏覽

將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&#39;+type, handler); 
} 
} 
function saveImageInfo () 
{ 
var mycanvas = document.getElementById("thecanvas"); 
var image = mycanvas.toDataURL("image/png"); 
var w=window.open(&#39;about:blank&#39;,&#39;image from canvas&#39;); 
w.document.write("<img src=&#39;"+image+"&#39; alt=&#39;from canvas&#39;/>"); 
} 
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>

運行效果如下

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

關於HTML5 Canvas的事件處理

angularJS結合canvas畫圖的實作

##

以上是使用toDataURL實作將HTML5 Canvas的內容儲存為圖片的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn