html2canvas生成图片出现白边儿的解决方法

场景:页面中分享二维码海报,用html2canvas生成图片之后,因为底部有个按钮,页面有了滚动条,造成页面顶部白边

直接上代码

html

<div id="posterHtml">
    <div class="contentF flex jCenter column">
           <div v-if="isDown">
               <img :src="posterImg_" style="width: 100%;height: 100%;"/>
               <div class="titleText">成都武侯区航利包子铺</div>
               <img class="qrcode" :src="qrcode"/>
           </div>
            <img :src="posterImg" style="width: 100%;height: 100%;" v-if="!isDown"/>
    </div>
    <div style="margin: 12px 24px;" v-if="isDown">
           <van-button class="Btn" type="primary" @click="createPoster" block>点击生成分享海报</van-button>
     </div>
</div>

js

const vm = this;
const domObj = document.getElementById('posterHtml');
let scrollTop = document.documentElement.scrollTop||document.body.scrollTop;//获取窗口滚动条高度
    html2canvas(domObj, {
           useCORS: true,//Whether to attempt to load cross-origin images as CORS served, before reverting back to proxy
           allowTaint: false,//Whether to allow cross-origin images to taint the canvas
           height: domObj.offsetHeight,//Define the heigt of the canvas in pixels. If null, renders with full height of the window
           width: domObj.offsetWidth,
           windowWidth: document.body.scrollWidth,
           windowHeight: document.body.scrollHeight,
           logging: false,//Whether to log events in the console
           x: 0,
           y: scrollTop-74, // 用网页滚动的高度定位y轴顶点
           dpi: window.devicePixelRatio * 2,
           scale: 2,
//         backgroundColor: null,//Canvas background color, if none is specified in DOM. Set undefined for transparent
           letterRendering: true,//Whether to render each letter seperately. Necessary if letter-spacing is used
           onclone (doc) {
                  let e = doc.querySelector('#posterHtml');
                  e.style.display = 'block'
            }
            }).then(canvas => {
                    // 在微信里,可长按保存或转发
                    vm.posterImg = canvas.toDataURL('image/png');
                    vm.isDown = false;
                    console.log(vm.posterImg);
            })
    }

关键点在于获取滚动条高度来填充,另外最好是把画布的width和height加上

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。