html
? <div ref="imageWrapper" class="iswap"? id="imageWrapper">
<!--這里是省略的html內(nèi)容-->
? </div>
css
? #imageWrapper{
? ? ? ? width: 340px;
? ? ? ? height: 480px;
? ? ? ? overflow: visible !important;
? ? }
js,由于canvas在繪制過程中
? async down(){
? ? ? ? ? ? ? ? var _this = this
? ? ? ? ? ? ? ? window.scrollTo(0, 0);? ? //如果你的窗口滾動的話需要,
? ? ? ? ? ? ? ? let imageWrapper = document.getElementById('imageWrapper')
? ? ? ? ? await html2canvas(imageWrapper, {
? ? ? ? ? ? ? ? ? ? x: imageWrapper.getBoundingClientRect().left + 13,? ? // 繪制的dom元素相對于視口的位置却紧,由于獲取的位置比原本往前偏離的所以要加上,你需要根據(jù)自己的視圖去計算
? ? ? ? ? ? ? ? ? ? y:imageWrapper.getBoundingClientRect().top,? ? ? ? ? ? // top沒有偏離所以不用修改
? ? ? ? ? ? ? ? ? ? backgroundColor: null,? ? ? ? ? ? ? ? ? ? ? ? ? ? // 解決生成的圖片有白邊轴合,只單單加和這個并沒有效果
? ? ? ? ? ? ? ? ? ? width:imageWrapper.offsetWidth - 15,? ? ? ? ? ? ? ? ? // 因為多出的需要剪裁掉,
? ? ? ? ? ? ? ? ? ? height:imageWrapper.offsetHeight,
? ? ? ? ? ? ? ? ? ? useCORS: true,
? ? ? ? ? ? ? ? ? ? scale:3,? ? ? // 因為生成圖片會模糊碗短,但是這個會使下載的圖片變大受葛,可以使用base64壓縮
? ? ? ? ? ? ? ? ? ? dpi: window.devicePixelRatio, //z
? ? ? ? ? ? ? ? }).then(canvas => {
? ? ? ? ? ? ? ? ? ? const img = canvas.toDataURL("image/jpeg").replace("data:image/jpeg;base64,", "")
? ? ? ? ? ? ? ? ? ? const finalImageSrc = "data:image/jpeg;base64," + img
? ? ? ? ? ? ? ? ? ? // 添加a標(biāo)簽用于下載
? ? ? ? ? ? ? ? ? ? const aElem = document.createElement('a')
? ? ? ? ? ? ? ? ? ? document.body.appendChild(aElem)? // 223kb
? ? ? ? ? ? ? ? ? ? aElem.href? = finalImageSrc
? ? ? ? ? ? ? ? ? ? // 圖片下載名
? ? ? ? ? ? ? ? ? ? aElem.download = "erwei.jpg"
? ? ? ? ? ? ? ? ? ? aElem.click()
? ? ? ? ? ? ? ? ? ? document.body.removeChild(aElem) // 完成后移除
? ? ? ? ? ? ? ? })
? ? ? ? },