佳木斯湛栽影视文化发展公司

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

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

熱門標(biāo)簽:網(wǎng)站建設(shè) 美圖手機 阿里云 硅谷的囚徒呼叫中心 百度競價點擊價格的計算公式 使用U盤裝系統(tǒng) 檢查注冊表項 智能手機
主要思想是借助Canvas自己的API - toDataURL()來實現(xiàn),整個實現(xiàn)
HTML + JavaScript的代碼很簡單。

復(fù)制代碼
代碼如下:

<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>

運行效果如下

標(biāo)簽:湖北 賀州 湘潭 黃山 山南 煙臺 懷化 通遼

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《將HTML5 Canvas的內(nèi)容保存為圖片借助toDataURL實現(xiàn)》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    南开区| 青田县| 怀化市| 宕昌县| 沽源县| 区。| 鄢陵县| 新民市| 临武县| 塘沽区| 天台县| 海南省| 东乡族自治县| 商丘市| 吴川市| 黔西县| 娱乐| 吉水县| 思茅市| 黎平县| 马尔康县| 乐山市| 宜章县| 枣阳市| 广德县| 林口县| 福海县| 昌宁县| 安丘市| 徐汇区| 喜德县| 辉南县| 湄潭县| 化隆| 炎陵县| 托克逊县| 揭阳市| 泸州市| 沐川县| 宁明县| 衡南县|