【Uniapp】简易图片验证码

uniapp 简易图片验证码

<view class="pic" @click="picCodeRefresh">
  <canvas
    style="width:100%;height:100%"
    canvas-id="imgCanvas"
    @error="canvasIdErrorCallback"
  ></canvas>
</view>
methods: {
  // 刷新验证码
  picCodeRefresh() {
    this.picCodeInit()
  },
  // 随机数
  randomNum(min, max) {
    return parseInt(Math.random() * (max - min) + min)
  },
  // 随机rgb
  randomRgb(min, max) {
    let r = this.randomNum(min, max),
      g = this.randomNum(min, max),
      b = this.randomNum(min, max)
    return `rgb(${r},${g},${b})`
  },
  // 初始化验证码
  picCodeInit() {
    let context = uni.createCanvasContext('imgCanvas', this),
      poolArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'I', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'S', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
      // 验证码
      codeStr = ''
    context.setFillStyle('white')
    context.setLineWidth(5)
    context.fillRect(0, 0, 75, 32)
    for (let i = 0; i < 4; i++) {
      let c = poolArr[this.randomNum(0, poolArr.length - 1)],
        deg = this.randomNum(-30, 30)
      context.setFontSize(16)
      context.setTextBaseline('top')
      context.setFillStyle(this.randomRgb(80, 150))
      context.save()
      context.translate(17 * (i + 1), 24)
      context.rotate((deg * Math.PI) / 180)
      context.fillText(c, -15 + 5, -15)
      context.restore()
      codeStr += c
    }
    // 同步验证码
    this.picCode = codeStr.toLowerCase()
    for (let i = 0; i < 100; i++) {
      context.beginPath()
      context.arc(this.randomNum(0, 75), this.randomNum(0, 32), 1, 0, 2 * Math.PI)
      context.closePath()
      context.setFillStyle(this.randomRgb(150, 200))
      context.fill()
    }
    context.draw()
  },
  // canvas异常处理
  canvasIdErrorCallback({ detail: { errMsg } }) {
    console.log(errMsg)
  }
},
onShow() {
  // dom渲染完毕后初始化图片验证码
  this.$nextTick(() => this.picCodeInit())
},
posted @ 2020-12-30 10:40  [ABing]  阅读(655)  评论(0编辑  收藏  举报