• 使用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()
      }
    }
  • 相关阅读:
    js基础 数组reduce
    js基础 数组every some
    js基础 数组forEach
    js基础 数组排序
    js基础 数组findIndex
    nodejs+koa2微信app支付,小程序支付
    Iview-datePicker获取选中的日期,如果没有选,提示错误,选了,错误隐藏
    mongoose+koa2 按照_id更新多条数据,删除数组中的字段,然后添加新的字段,$pull和$or结合使用
    json数组去除重复的值
    mongoose根据_id更新,且如果数组中没有元素就添加
  • 原文地址:https://www.cnblogs.com/Awen71815iou/p/11713429.html
Copyright © 2020-2023  润新知