html2canvas使用
引入
import html2canvas from 'html2canvas'
使用
//获取详情 getinfo(hid,sign){ this.loading=true this.$apiRequest('details', { "hid":Number(hid), "sign":sign }).then(res => { this.info = res.data // alert(res.data.avatar) this.$nextTick(()=>{ if(res.data.poster_type==="0"){ this.$nextTick(()=>{ setTimeout(()=>{ let poster = document.getElementById("haibaoone"); this.createImg(poster) },500) }) }else if(res.data.poster_type==="1"){ setTimeout(()=>{ let poster = document.getElementById("haibaotwo"); this.createImg(poster) },500) } }) }) }, //生成图片 createImg(dom) { //const poster = document.getElementById("haibao"); let that = this html2canvas(dom, { dpi: 80, useCORS: true, scale: 4, async: true, // width: dom.offsetWidth, // height: dom.offsetHeight x: that.getActuralPosition(dom).left + parseInt(that.getScrollWidth()/2), y: that.getActuralPosition(dom).top, }).then((canvas) => { this.imgSrc = canvas.toDataURL("image/jpeg"); this.showdiv = false this.loading=false //console.log(this.imgSrc) }).catch(() => { }) }, //获取网页元素的绝对位置 getActuralPosition(element){ let acturalLeft = element.offsetLeft; let acturalTop = element.offsetTop; let curElement = element.offsetParent; while(curElement){ acturalLeft += curElement.offsetLeft; acturalTop += curElement.offsetTop; curElement = curElement.offsetParent; } return { left: acturalLeft, top: acturalTop, } }, // 获取滚动条的宽度 getScrollWidth() { // 创建一个div元素 let noScroll, scroll, oDiv = document.createElement('DIV'); oDiv.style.cssText = 'position:absolute; top:-1000px; width:100px; height:100px; overflow:hidden;'; // 没有滚动条的clientWidth clientWidth为content+paddingLeft+paddingRight 不包括滚动//条,可以利用这个获取差值来求滚动条的宽度 noScroll = document.body.appendChild(oDiv).clientWidth; oDiv.style.overflowY = 'scroll'; scroll = oDiv.clientWidth; document.body.removeChild(oDiv); return noScroll-scroll; },