使用js插件html2canvashttp://html2canvas.hertzen.com/
使用场景:把html页面标签id="saveImgBox" 的内容,转为规定尺寸的图片,下载到本地
<!--html-->
<style>
#saveImgBox{
position:fixed;
left:0;
top:0;
opacity:0
}
</style>
<a target="_blank" download id="savImgBtn">保存图片</a>
<div id="saveImgBox">
内容省略
</div>
注意:如果要渲染的部分包含图片,图片必须在当前同一个域下,如下图官方文档说明。
1.绘制要下载的图片区域画布
//js
var w = $("#saveImgBox").width();
var h = $("#saveImgBox").height();
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var scaleBy = 1
canvas.width = w * scaleBy;
canvas.height = h * scaleBy;
canvas.width = w * scaleBy;
canvas.height = h * scaleBy;
canvas.style.width = w + "px";
canvas.style.height = h + "px";
context.scale(scaleBy, scaleBy);
2.使用html2canvas渲染图像并下载
//js
var filename = "自定义图片名"
html2canvas($("#saveImgBox")[0], {
allowTaint: true,
taintTest: false,
canvas: canvas,
onrendered: function(canvas) {
var url = canvas.toDataURL("image/png"); //转为base64,设置图片格式为png
var download = $("#savImgBtn").attr("href", url).attr("download",filename);
download[0].click();
}
});