首頁 >web前端 >H5教程 >將HTML5 Canvas的內容儲存為圖片借助toDataURL實作_html5教學技巧

將HTML5 Canvas的內容儲存為圖片借助toDataURL實作_html5教學技巧

WBOY
WBOY原創
2016-05-16 15:49:281349瀏覽

主要想法是藉助Canvas自己的API - toDataURL()來實現,整個實作
HTML JavaScript的程式碼很簡單。

複製程式碼
程式碼如下:



-equiv="X-UA-Compatible" content="chrome=1">

<script> <br />window.onload = function() { <br />draw(); <br />var saveButton = document.getElementById("saveImageBtn"); <br />bindButtonEvent(saveButton, "click", saveImageInfo); <br />var dlButton = document.getElementByfee( click", saveAsLocalImage); <br />}; <br />function draw(){ <br />var canvas = document.getElementById("thecanvas"); <br />var ctx = canvas.getContext("2d"); <br />ctx.fillStyle = "rgba(125, 46, 138, 0.5)"; <br />ctx.fillRect(25,25,100,100); <br />ctx.fillStyle = "rgba( 03, 85,03, 805) ; <br />ctx.fillRect(58, 74, 125, 100); <br />ctx.fillStyle = "rgba( 0, 0, 0, 1)"; // black color <br />ctx.fillText("omyfish - Demo", 50, 50); <br />} <br />function bindButtonEvent(element, type, handler) <br />{ <br />if(element.addEventListener) { <br />element.addEventListenerener(type, handler, false); <br />} else { <br />element.attachEvent('on' type, handler); <br />} <br />} <br />function saveImageInfo () <br />{ <br />var mycanvas = document .getElementById("thecanvas"); <br />var image = mycanvas.toDataURL("image/png"); <br />var w=window.open('about:blank','image from canvas'); <br />w.document.write("<img src='" image "' alt='from canvas'/>"); <br />} <br />function saveAsLocalImage () { <br />var myCanvas = document.getElementById( "thecanvas"); <br />// here is the most important part because if you dont replace you will get a DOM 18 exception. <br />// var image = myCanvas.toDataURL("image/png").replace( "image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png"); <br />var image = myCanvas.toDataURL("image/png").replace("image/png ", "image/octet-stream"); <br />window.location.href=image; // it will save locally <br />} <br /></script>







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