使用canvas畫布生成二維碼


1. 基本用法

<canvas>標簽只有兩個屬性-----width和height

CSS:

<canvas class="qrcode" width="100%" height="100%"></canvas>

<canvas>元素只是創造了一個固定大小的畫布,要想在它上面繪制內容,我們需要找到它的渲染上下文,

<canvas>元素有一個叫做 getContext()的方法,而這個方法就是用來獲得渲染上下文和它的繪畫功能。

JS:

imageToCanvsa () {
  let that = this
  let canvas = document.createElement('canvas')   // 獲取canvas對象(通過選擇器選擇canvas元素)
  let ctx = canvas.getContext('2d')  // 獲得渲染上下文和他的繪畫功能
  // 將二維碼的canvas轉化成base64
  let qrcode = new Image ()
  qrcode.crossOrigin = 'Anonymous'
  qrccode.src =  document.querySelector('.qrcode').toDataURL()
  let img = new Image()
  img.crossOrigin = 'Anonymous'
  img.src = that.appData.share.img[that.currentIdx].img_url
  img.onload = fuction () {
    canvas.width = img.width // 畫板寬
    canvas.height =img.height // 畫板高
    // 畫圖
    // 參數:圖片對象、相對畫布的起點x坐標、相對畫布的起點y坐標、繪制的圖片寬度(二維碼,px)、繪制的圖片高度(二維碼,px)
    ctx.drawImage(img, 0, 0, img.width, img.height)
    ctx.drawImage(qrcode, img.width * 0.3, img.height * 0.65, img.width * 0.4, img.width * 0.4)
    ctx.fillStyle = '#fff' // 定義用白色填充矩形
    // 繪制“已填充”的矩形
    // 參數:矩形左上角的x坐標、矩形左上角的y坐標、矩形寬(像素)、矩形高(像素
    ctx.fillRect(img.width * 0.3, img.height * 0.878, img.width * 0.4, img.height * 0.035)
    ctx.fillStyle = '#000'
    ctx.font = 'normal 28px Arial'
    ctx.textBaseline = 'middle' // 文本基線在正中
    // 在畫布上繪制"被填充"的文本
    // 參數:規定在畫布上輸出的文本、開始繪制文本的x坐標、開始繪制文本的y坐標
    ctx.fillText(`邀請碼:${that.nikname}`, img.width * 0.5, img.height * 0.896)
    that.poster = canvas.toDataURL()
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM