html2canvas.js插件截图空白问题和微信长按图片分享失败问题
发现使用
html2canvas.js插件截图保存在前端很方便。学习过程中遇到的问题,主要负责将html标签转化为图片。
canvas2image.js是一个展示图片的canvas插件,解决微信分享失败就靠这个插件。
截图出现空白和截图不全。
如果要截取图片为圆角,且圆角为透明情况处理。(问题新增20200929)
问题原因:
html2canvas.js插件截图是基于body标签的,如果body存在滚动条就会出现截图空白的情况。如何避免:
关键点:在截图前将滚动条位置设置在顶部。截图时,截图选择内容标签不是body,就将截图宽度和高度设置为选择标签的宽高在截图。
处理圆角透明方案:将需要截取的div的背景的css样式 background 设置为一个url图片。在截图时就不会出现圆角变为白色背景了。
具体代码:
<script src="jquery-1.11.1.min.js"></script>
<script src="https://cdn.bootcss.com/html2canvas/0.4.1/html2canvas.js"></script>
<style>
/* 海报 解决圆角白色背景的关键css为:background: url(poster.jpg) no-repeat; */
.poster{min-height: 100vh;height: 100vh;background: url(poster.jpg) no-repeat;background-size: 100% 100%;position: relative; border-radius: 50px;}
.poster .qrcode{position: absolute;width: 2.5rem;height: 2.5rem;background: #5a13c9;border: 3px solid #00cd7f;border-radius: .2rem;text-align: center;bottom: 31%;left: 0;right: 0;margin: 0 auto;}
.poster .qrcode img{width: 2.36rem;height: 2.36rem;margin-top: 3px;}
</style>
<!-- 海报弹窗 --> <div class="dialog flex" id="alert10" style="display:none" > <div class="poster_con"> <div class="poster" id="contbox"> <div class="qrcode" id="qrcode"> </div> </div> <div class="poster_btn"><button id="down">点击保存图片分享给好友</button><a id="down1" class="down" href="" download="downImg" style="display:none"></a></div>
</div> </div>
浏览器
下载图片js代码:
$("#down").click(function(){
// 截图前先讲滚动条置顶
$('html,body').animate({'scrollTop':0});
// document.getElementById("contbox") 需要截图的是div标签
html2canvas(document.getElementById("contbox"),
{logging:false,
width:$("#contbox").width(),// 宽设置为div标签的宽
height:$("#contbox").height(),// 高设置为div标签的高
useCORS:true}).then(function(canvas) {
//将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
var timestamp = Date.parse(new Date());
//把截取到的图片替换到a标签的路径下载
$("#down1").attr('href',canvas.toDataURL("image/png"));
console.log(canvas.toDataURL("image/png"));
//下载下来的图片名字
$("#down1").attr('download',timestamp + '.png') ;
$("#down1")[0].click();
//document.body.appendChild(canvas);
});
});
微信分享长按图片分享js代码:
$("#down").click(function(){
// 截图前先讲滚动条置顶
$('html,body').animate({'scrollTop':0});
$('body').css({'overflow':'hidden'})
// document.getElementById("contbox") 需要截图的是div标签
html2canvas(document.getElementById("contbox"),
{logging:false,
width:$("#contbox").width(),// 宽设置为div标签的宽
height:$("#contbox").height(),// 高设置为div标签的高
useCORS:true}).then(function(canvas) {
// 将canvas转为图片
var img = Canvas2Image.convertToImage(canvas,$("#contbox").width()*2,
$("#contbox").height()*2);
// 图片添加到页面中,在微信里长按添加的img图片就可以正常使用微信自带的长按图片分享功能
$('body').append(img);
$('body').css({'overflow':'scroll'})
});
});
将一些逻辑问题使用代码实现
浙公网安备 33010602011771号