濮阳杆衣贸易有限公司

主頁 > 知識庫 > 將HTML5 Canvas的內(nèi)容保存為圖片借助toDataURL實現(xiàn)

將HTML5 Canvas的內(nèi)容保存為圖片借助toDataURL實現(xiàn)

熱門標簽:臨海地圖標注app 四川移動電銷外呼客戶管理系統(tǒng) 百度地圖標注為什么總是封號 怎么做百度地圖標注 400開頭的電話好申請不 智能芯電話機器人 小朱地圖標注 咸陽穩(wěn)定外呼系統(tǒng)軟件 地圖標注柱狀圖
主要思想是借助Canvas自己的API - toDataURL()來實現(xiàn),整個實現(xiàn)
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>

運行效果如下

標簽:平頂山 陜西 公主嶺 黃石 黃石 山南 南平

巨人網(wǎng)絡通訊聲明:本文標題《將HTML5 Canvas的內(nèi)容保存為圖片借助toDataURL實現(xiàn)》,本文關(guān)鍵詞  將,HTML5,Canvas,的,內(nèi)容,保,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《將HTML5 Canvas的內(nèi)容保存為圖片借助toDataURL實現(xiàn)》相關(guān)的同類信息!
  • 本頁收集關(guān)于將HTML5 Canvas的內(nèi)容保存為圖片借助toDataURL實現(xiàn)的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    贡觉县| 霍山县| 罗定市| 平昌县| 娄底市| 威海市| 沙坪坝区| 元氏县| 马尔康县| 淮安市| 英德市| 永年县| 巴彦淖尔市| 庆安县| 正阳县| 治多县| 寿光市| 康平县| 平阳县| 遂溪县| 香格里拉县| 屯留县| 静海县| 惠东县| 长治县| 无极县| 林芝县| 内乡县| 奉化市| 梅河口市| 渭源县| 海阳市| 互助| 汝阳县| 赣榆县| 五指山市| 塔河县| 林口县| 浦城县| 德州市| 贵阳市|