纯javaScriptdiv保存图⽚并下载js+Canvas+Svg 最精简的原⽣js开发,更⽅便扩展开发需要的业务
技术逻辑:
1.将div转为svg⽹络图⽚
2.将创建Canvas画布
3.将画布⼤⼩和div⼤⼩设置⼀样⼤
4.将svg img 画到Canvas的画布中 ⽤⽅法  context.drawImage(img, 0, 0);
5.将Canvas画布保存为png图像
⽰例程序截图:
CODE:
<html>
<body>
<h2>Input Div:</h2>
<div id="div">
<p>Just have a <span style='color: white; text-shadow: 0 0 2px blue;'>TRY</span></p>
<p><b>By Dion</b></p>
<div >
<div >
<div >
<div >
<div >
这是图⽚5</div>
这是图⽚4
</div>
这是图⽚3
</div>
这是图⽚2
</div>
这是图⽚1
</div>
</div>
<h2>Output Image:</h2>
<input type="button" value="⽣成图⽚" onClick="printMap()">
<input type="button" value="下载图⽚" onClick="saveMap()">
<div id="ssssssssssss" ></div>    <script>
var imgObj;
function printMap() {
//1.将div转成svg
var divContent = ElementById("div").innerHTML;
var newData = "";
原生js和js的区别
for ( var i = 0; i < divContent.length; i++) {
if (divContent.substr(i, 1) == "#") {
newData += '%23';
} else {
newData += divContent.substr(i, 1);
}
}
var data = "data:image/svg+xml,"
+ "<svg id='abcdddd' xmlns='/2000/svg' width='600' height='500'>"
+ "<foreignObject width='100%' height='100%'>"
+ "<div xmlns='/1999/xhtml' style='font-size:16px;font-family:Helvetica'>"
+ newData + "</div>" + "</foreignObject>" + "</svg>";
var img = new Image();
img.src = data;
// ElementsByTagName('body')[0].appendChild(img);
imgObj = img;
}
function saveMap() {
var img = imgObj;//ElementById("ssssssssssss").getElementsByTagName("img");
//2.svg转成canvas
var canvas = ateElement('canvas'); //准备空画布
canvas.width = img.width;
canvas.height = img.height;
var context = Context('2d'); //取得画布的2d绘图上下⽂
context.drawImage(img, 0, 0);
var type = 'png';
var imgData = DataURL(type);
// 加⼯image data,替换mime type
imgData = place(_fixType(type), 'image/octet-stream');            // 下载后的图⽚名
var filename = 'baidufe_' + (new Date()).getTime() + '.' + type;
// download
saveFile(imgData, filename);
}
var _fixType = function(type) {
type = LowerCase().replace(/jpg/i, 'jpeg');
var r = type.match(/png|jpeg|bmp|gif/)[0];
return 'image/' + r;
};
var saveFile = function(data, filename) {
var save_link = ateElementNS(
'/1999/xhtml', 'a');
save_link.href = data;
save_link.download = filename;
var event = ateEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0,
false, false, false, false, 0, null);
save_link.dispatchEvent(event);
};
</script>
</body>
</html>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。