canvas-img互相转化 和合成img

贴一段代码先

 methods: {
           // polyfill 提供了这个方法用来获取设备的 pixel ratio 
          getPixelRatio: function (context) { 
            var backingStore = context.backingStorePixelRatio ||
                context.webkitBackingStorePixelRatio ||
                context.mozBackingStorePixelRatio ||
                context.msBackingStorePixelRatio ||
                context.oBackingStorePixelRatio ||
                context.backingStorePixelRatio || 1;
            return (window.devicePixelRatio || 1) / backingStore;
          },
          _drawBg: function() {
            var c = this.$refs.composeWapper; //vue取dom
            var cxt = c.getContext("2d"); //获取画布
            var radio = this.getPixelRatio(cxt); //获取像素比
            var img = new Image(); 
           //Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
            img.crossOrigin = "anonymous"; //不同源图片配置跨域  
            var thisWh = window.innerWidth;
            var thishg = window.innerWidth* 1.55;
            c.width = thisWh * radio; //先设置canvas w,h为radio倍
            c.height = thishg * radio;
            cxt.scale(radio, radio);  //画布需要进行radio倍的缩放防止生成base64图片失真
            img.src = "${staticCtx}/wap/img/my_invitation/qr-code-bg.png"; //该img 和下面的img不在一个域下
            img.onload = function() {  //img load后才能进行下操作
              cxt.drawImage(img, 0, 0, thisWh, thishg);  //将img写入canvas
              var winWh = window.innerWidth;
              c.style.width = winWh + 'px';  //通过style还原到正常的h,w
              c.style.height = winWh* 1.55 + 'px';
              var codeImg = this.$refs.codeWapper.$el.children[1]; //获取动态生成的二维码dom
              cxt.drawImage(codeImg, winWh* 0.255, winWh* 0.267, winWh* 0.485, winWh* 0.485);
              this.composeImg  = c.toDataURL("image/png");  //canvas装换为base64码
            }.bind(this)
          }
        },
        created: function () {},
        mounted: function () {
          this._drawBg();
        },

多张图片通过canvas合成跨域问题

Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

需要给img设置跨域头 img.crossOrigin = "anonymous"; //不同源图片配置跨域

canvas导出img 出现图片失真的情况

参照上面的代码

你可能感兴趣的:(canvas-img互相转化 和合成img)