vue的html2canvas将dom转化为图片时踩得坑
一、html2canvas中图片涉及跨域图片
应用场景:做个投票活动,将参赛者的信息转化成图片截图分享。用户上传图片上传到腾讯云cos桶中,html2canvas只能转换本地资源的图片,涉及跨域的图片无法转换、
解决方法:通过nginx代理转发,
假设你的网站是 http://www.helloworld.com
把 https://dingzi-1258648408.cos.ap-chengdu.myqcloud.com/upload/f49a6da3-73ea-422a-9b63-7a3e522130e2.png
换成 http://www.helloworld.com/cosImageUrl/upload/f49a6da3-73ea-422a-9b63-7a3e522130e2.png
这样访问http://www.helloworld.com/cosImageUrl就代理成https://dingzi-1258648408.cos.ap-chengdu.myqcloud.com/
- 配置nginx,在80端口下的localtion中添加一条配置
location /cosImageUrl/ { proxy_http_version 1.1; proxy_pass https://dingzi-1258648408.cos.ap-chengdu.myqcloud.com/; add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods "POST, GET, OPTIONS"; add_header Access-Control-Allow-Headers "Origin, Authorization, Accept"; add_header Access-Control-Allow-Credentials true; }
- 图片地址换成http://www.helloworld.com/cosImageUrl/upload/f49a6da3-73ea-422a-9b63-7a3e522130e2.png
- vue文件中
<div ref="imageWrapper" v-if="firstFlag"></div> <div class="show_img"> <img :src="dataURL" alt="" v-if="!firstFlag" style="width: 100%"> </div>
import html2canvas from "html2canvas" export default { name: "share", data() { return { firstFlag: true, dataURL: '', } }, methods: { toImg() { html2canvas(this.$refs.imageWrapper,{useCORS: true}).then(canvas => { let imgUrl = canvas.toDataURL('image/png'); this.dataURL = imgUrl; this.firstFlag = false; }).catch(error => { }) }, }, mounted() { const that = this; that.$nextTick(function () { that.toImg(); }); },
二、转化图片后截取部分背景图模糊,图片有空白部分
- 展示太快,内容没有加载完,解决方法:设置延时
setTimeout(() => { html2canvas() },500)
- 内容太多,html2canvas是根据body进行截图,若内容高度高于body时,就会出现这样的问题(大概意思就是有滚动条时造成的) 解决方法:讲滚动条置顶
window.pageYOffset = 0; document.documentElement.scrollTop = 0 document.body.scrollTop = 0
- 设置生成图片的大小
html2canvas(that.$refs.imageWrapper,{useCORS: true, width:window.screen.availWidth, //canvas宽度 height:window.screen.availHeight, //canvas高度 windowWidth:document.body.scrollWidth, //获取X轴方向滚动条内容 windowHeight:document.body.scrollHeight/1.06,//获取Y轴方向滚动条内容 x:0,//页面在水平方向滚动的距离 y:0,//页面在垂直方向滚动的距离 }).then(canvas => { let imgUrl1 = canvas.toDataURL('image/png'); that.dataURL = imgUrl1; that.firstFlag = false; // this.firstFlag = false; }).catch(error => { })