vue使用canvas完成二維碼與圖片的合成與下載(兩張圖片同理)

<el-dialog :title="title" :visible.sync="shopCodeShow" :append-to-body="true" width="20%" height="480">
  <div class="bg-purple-light-down limit-button">
    <el-button type="primary" plain size="small" @click="downLoadShopPic">下載</el-button>
  </div>
  <div style="display: flex;justify-content: center; margin-top:10px;">
    <img ref="shopPicImg" :src="shopPic"  style="display: none;" alt="店鋪背景">
    <vue-qr :callback="f_shopPicCode"  :text="payPic" :logoSrc="paylogoSrc" :size="150" :logoScale="0.3" :margin=0 style="display: none; "></vue-qr>
    <canvas id="myCanvasShopPic" ref="myCanvas" width="300" height="450" style="border:1px #eeeeee solid;"></canvas>
  </div>
</el-dialog>
//畫布畫店鋪碼
toShopCode (rowData) {
  this.shopNameBgImg = "";
  this.title = '店鋪碼';
  this.shopCodeShow = true;
  this.unable = false;
  this.shopPicCode = rowData.CommonQRcode;
  this.paylogoSrc = require('../../../assets/aggLogo.png');
  this.shopNameBgImg = rowData.Name;

  this.$nextTick(function () {//等待加載完成
    // 獲取Canvas 畫圖
    let myCanvas = this.$refs.myCanvas
    var ctx = myCanvas.getContext('2d');
    // 在Canvas畫布 添加圖片
    var img = this.$refs.shopPicImg;
    img.setAttribute("crossorigin","anonymous");
    img.setAttribute("src","url"+'?time=' + new Date().valueOf())
    img.onload = () => {
      ctx.drawImage(img, 0, 0, 300, 450);
    }
  })
},

//店鋪二維碼回調
f_shopPicCode(dataUrl,id){
  var shopNameBgImg = this.shopNameBgImg
  this.shopPicCodeUrl = dataUrl;
  let myCanvas = this.$refs.myCanvas
  var ctx = myCanvas.getContext('2d')
  ctx.clearRect(0,0,300,450);
  // 在Canvas畫布 添加圖片
  // var shopPicCodeImg = this.$refs.shopPicCodeImg;
  var shopPicCodeImg = new Image();
  shopPicCodeImg.src = dataUrl;
  // shopPicCodeImg.setAttribute("src",dataUrl)
  shopPicCodeImg.onload = () => {
    ctx.drawImage(shopPicCodeImg, 65, 120, 170, 170);
    ctx.globalCompositeOperation = "destination-over";//層級關係,二維碼放在上層
    ctx.font = "14px bold 黑體";
    ctx.fillStyle = "#ffffff";
    ctx.textAlign = "center";
    // 設置垂直對齊方式
    ctx.textBaseline = "middle";
    // 繪製文字
    ctx.fillText(shopNameBgImg, 140, 90);
  }
},
//下載店鋪碼
downLoadShopPic(){
  var myCanvasShopPic  = document.getElementById("myCanvasShopPic");
  var dataURL = myCanvasShopPic.toDataURL("image/png");
  var saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
  saveLink.href = dataURL;
  saveLink.download = 'downLoad.png';
  saveLink.click();
},

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章