溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

將HTML5 Canvas的內容保存為圖片

發(fā)布時間:2020-06-17 04:17:08 來源:網絡 閱讀:597 作者:gloomyfish 欄目:移動開發(fā)

主要思想是借助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('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"> 	<div> 		<canvas width=200 height=200 id="thecanvas"></canvas> 		<button id="saveImageBtn">Save Image</button> 		<button id="downloadImageBtn">Download Image</button> 	</div> </body> </html>

運行效果如下:

將HTML5 Canvas的內容保存為圖片


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI