1.前臺使用html2canvas js 截取Div元素轉存爲圖片,下載。效果:javascript
2.前臺代碼html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
<script src="Html2canvas_JS/html2canvas.min.js"></script>
<script src="Html2canvas_JS/canvas2image.js"></script>
</head>
<body>
<div id="div1" style="width: 200px; height: 450px; border: silver 1px solid; ">
<img src="Images/imgDemo.jpg" style="width: 160px; height: 160px; margin-left: 20px; margin-right: 20px; margin-top: 40px;"/>
<label style="text-align: center;display:block"><b>王二小</b><br/></label>
<label style="text-align: center;display:block">王二小喜歡放牛<br/></label>
<div align="center">
王二小喜歡放牛,<br />
王二小喜歡放牛,<br />
王二小喜歡放牛,<br />
王二小喜歡放牛 <br />
</div>
</div>java
<div id="img" style="display: none; width: 200px; height: 450px; position: absolute; top: 8px; left: 216px;"></div>
<button id="btnCreateImg">生成圖片</button>
<button id="btnSaveImg">下載圖片</button>
</body>
<script type="text/javascript">
var content = document.getElementById("div1");
var btn = document.getElementById("btnCreateImg");
btn.onclick = function() {
html2canvas(content, {
useCORS: true, //容許跨域
onrendered:function(canvas) {
canvas.setAttribute("id", "thecanvas");
document.getElementById("img").innerHTML = "";
document.getElementById("img").appendChild(canvas);
}
});
window.alert('生成圖片成功');
};
var btnDownload = document.getElementById("btnSaveImg");
btnDownload.onclick = function () {
var timestamp = Date.parse(new Date());
var fileName = timestamp + ".PNG";
var oCanvas = document.getElementById("thecanvas");
var img_data1 = Canvas2Image.saveAsPNG(oCanvas, true).getAttribute("src");
//下載保存
saveFile(img_data1, fileName);
//此種方法將直接下載文件,可是不帶有圖片後綴名
//Canvas2Image.saveAsPNG(oCanvas);
window.alert('下載完成');
};
var saveFile = function (data, fileName) {
var link = document.createElement('a');
link.href = data;
link.download = fileName;
link.title = "";
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, true);
link.dispatchEvent(event);
};
</script>
</html>canvas
3.須要的js文件:跨域
canvas2image.jsapp
html2canvas.min.jsui
圖片:spa