填坑填坑 此处填个坑,项目中用到了html2canvas来把一个分享的弹窗,合成图片再分享出去,然后因为自己太菜了,掉坑里了一顿折腾,所幸后来填了坑,此篇记录一下,给大伙排坑!!!
如果想更深入学习,可自行查看官网: http://html2canvas.hertzen.com/
1.安装 npm install --save html2canvas 或者 yarn add html2canvas
2.页面引入 import html2canvas from ‘html2canvas’
3.html2canvas截图不全的问题, 我排查了很久,最后发现是布局的问题,好吧,那只能改
html2canvas 不认识height: 100%,建议更改为100vh,但是要想要两端固定中间滚动的话,中间自适应更好flex:1,这样就实现头部底部固定中间可滑动啦~
html2canvas截图是对整个DOM进行截图
<img :src="refShareContext" style="border: 1px solid red" alt="" />
const handleClickCreateCanvasImg = () => {
const shareContextDom = document.querySelector('.share-context')! as HTMLElement
return html2canvas(shareContextDom, {
scrollY: 0,
useCORS: true,
scale: window.devicePixelRatio,
}).then((canvas) => {
refShareContext.value = canvas.toDataURL('image/png', 1.0)
// replace('data:image/png;base64,', '') 转base64
})
}
4.截图图片被拉伸的以及不清晰问题
涉及图片基本处理https://developer.qiniu.com/dora/1279/basic-processing-images-imageview2
归根结底还是因为html2canvas 不认识object-fit: cover;,那么如何实现图片裁剪呢,可以通过用img标签来引入,再用div包裹住img,通过定位处理成和背景一样,这样图片就清晰了,
<div v-for="(item, index) in computedShareListImgClip" :key="index" class="photo-wall__warper--item">
<img :src="item.picture + '?imageView2/1/w/588/h/738/q/95'" alt="" />
</div>
//?imageView2/1/w/588/h/738/q/95 图片分辨率,让图片更快加载
.photo-wall__warper--item {
width: 196px;
height: 246px;
border-radius: 20px;
overflow: hidden;
margin-top: 32px;
margin-left: 33px;
display: flex;
justify-content: center;
position: relative;
img {
width: 100%;
}
}
很简单的操作,我卡了蛮久,总而言之,还是学习的少哈哈哈哈