<section class="page page4-star" style="z-index: 2;">
<div class="page4-group2">
<div class="page4-img-group1" id="page4-img-group" style="top:0;z-index: -1;">
<img class="page5-logo" src="img/page5_logo.png" alt="">
<div class="page4-img-bg">
<img id="page5_field_bg" src="img/page4_field_bg1.png" alt="">
</div>
<div class="page4-car-bg">
<img id="page5-car-img" src="img/page4_car_bg1.png" alt="">
</div>
<div class="page4-sticker-bg">
<img id="page5-sticker-img" src="img/page4_sticker_bg1.png" alt="">
</div>
<div class="page4-declaration-bg" id="page5-declaration-bg">
</div>
<div class="page5-record">
<p id="page5-personnel-num"></p>
<img class="page5-code" src="img/page5_code.png" alt="">
</div>
</div>
</div>
</section>
<section class="main-container">
<footer class="footer-center">
<button class="btn-share" style="position: fixed;bottom: 0;z-index: 9999;" id="btnShare">截 图</button>
</footer>
</section>
<img id="save" />
function $(selector) {
return document.querySelector(selector);
}
var main = {
init:function(){
main.setListener();
},
//设置监听事件
setListener:function(){
var btnShare = document.getElementById("btnShare");
btnShare.onclick = function(){
main.html2Canvas();
}
},
//获取像素密度
getPixelRatio:function(context){
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
},
//绘制dom 元素,生成截图canvas
html2Canvas: function () {
var shareContent = $("#page4-img-group");// 需要绘制的部分的 (原生)dom 对象 ,注意容器的宽度不要使用百分比,使用固定宽度,避免缩放问题
var width = shareContent.offsetWidth; // 获取(原生)dom 宽度
var height = shareContent.offsetHeight; // 获取(原生)dom 高
var offsetTop = shareContent.offsetTop; //元素距离顶部的偏移量
var canvas = document.createElement('canvas'); //创建canvas 对象
var context = canvas.getContext('2d');
var scaleBy = main.getPixelRatio(context); //获取像素密度的方法 (也可以采用自定义缩放比例)
console.log(scaleBy);
scaleBy = 3;
canvas.width = width * scaleBy; //这里 由于绘制的dom 为固定宽度,居中,所以没有偏移
canvas.height = (height + offsetTop) * scaleBy; // 注意高度问题,由于顶部有个距离所以要加上顶部的距离,解决图像高度偏移问题
context.scale(scaleBy, scaleBy);
var opts = {
allowTaint:true,//允许加载跨域的图片
tainttest:true, //检测每张图片都已经加载完成
scale:scaleBy, // 添加的scale 参数
canvas:canvas, //自定义 canvas
logging: true, //日志开关,发布的时候记得改成false
width:width, //dom 原始宽度
height:height //dom 原始高度
};
html2canvas(shareContent, opts).then(function (canvas) {
console.log("html2canvas");
alert(canvas.toDataURL())
var body = document.getElementsByTagName("body");
canvas.style.width = canvas.width / scaleBy + "px";
canvas.style.height = canvas.height / scaleBy + "px";
// body[0].appendChild(canvas);
var src = canvas.toDataURL();
var img = document.getElementById("save");
save.src = src;
save.style.width = canvas.style.width;
save.style.height = canvas.style.height;
// console.log(src);
});
}
};
//最后运行代码
main.init();
把代码放到服务器上可生成图片成功