应用场景:做个投票活动,将参赛者的信息转化成图片截图分享。用户上传图片上传到腾讯云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/

  1. 配置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;
      }
    

      

  2. 图片地址换成http://www.helloworld.com/cosImageUrl/upload/f49a6da3-73ea-422a-9b63-7a3e522130e2.png 
  3. 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();
          });
        },
    

      

12-18 11:17