微信小程序canvas2d生成图形验证码(新)

成品展示:

背景:

大致看了一下网上已经有一些canvas生成图形验证码的demo,发现使用的也只是旧版canvas,相比于新版canvas2d性能上略有差距,更重要的是旧版canvas在开发者工具上报警告,唉哟我这暴脾气,非得整成canvas2d的不成。成果记录在此。

wxml:

<input class="input font_14" placeholder-class="grey" type="text" 
    placeholder="输入图形验证码" maxlength="4" model:value="{{guiCode}}"
    bindinput="bindinput" />
<canvas class="guiCode" type="2d" id="guiCodeCanvas" bindtap="guiCodeTap" />

wxss:

.input {
    width: calc(165vmin / 3.75);
    height: 100%;
    padding: 0 calc(12vmin / 3.75);
    box-sizing: border-box;
}

.guiCode {
    width: calc(70vmin / 3.75);
    height: 100%;
}

js:

var guiCode = require('../../utils/guiCode.js');
const app = getApp()

Page({

    data: {
        guiCode: ''
    },

    onLoad: function (options) {
        this.guiCode = new guiCode({
            el: '#guiCodeCanvas',
            width: 70,
            height: 50,
            createCodeImg: ""
        })
    },

    bindinput() {},

    /**
     * 刷新图形验证码
     */
    guiCodeTap() {
        this.guiCode.refresh()
    },

    /**
     * 验证图形验证码
     */
    validateGuiCode() {
        if (!this.data.guiCode) {
            wx.showToast({
                title: '请输入图形验证码',
                icon: 'none'
            })
            return
        }
        let res = this.guiCode.validate(this.data.guiCode)
        if (!res) {
            wx.showToast({
                title: '图形验证码错误',
                icon: 'none'
            })
        }
    },

    /**
     * 立即验证按钮监听
     */
    toValidate() {
        //验证图形验证码
        this.validateGuiCode()
    },

})

guiCode工具类:

module.exports = class guiCode {
    constructor(options) {
        this.options = options
        this.init()
    }
    init() {
        // 注意:如果在组件中使用,请将这里的 wx 改为 this
        wx.createSelectorQuery().select(this.options.el)
                .fields({
                    node: true,
                    size: true
                }).exec((res) => {
                    this.canvas = res[0].node
                    this.ctx = this.canvas.getContext('2d')
                    this.canvas.width = this.options.width
                    this.canvas.height = this.options.height
                    this.fontSize = this.options.height * 3 / 6
                    this.ctx.textBaseline = "middle"
                    this.ctx.fillStyle = this.randomColor(180, 240)
                    this.refresh()
                })
    }
    refresh() {
        //清除上一次绘制
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
        var code = ''
        var txtArr = ['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', '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', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        for (var i = 0; i < 4; i++) {
            code += txtArr[this.randomNum(0, txtArr.length)]
        }
        this.options.createCodeImg = code
        let arr = (code + '').split('')
        if (arr.length === 0) {
            arr = ['e', 'r', 'r', 'o', 'r']
        }
        let offsetLeft = this.options.width * 0.6 / (arr.length - 1)
        let marginLeft = this.options.width * 0.2
        arr.forEach((item, index) => {
            this.ctx.fillStyle = this.randomColor(0, 180)
            let size = this.randomNum(18, this.fontSize)
            this.ctx.font = size + "px Arial"
            let dis = offsetLeft * index + marginLeft - size * 0.3
            let deg = this.randomNum(-30, 30)
            this.ctx.translate(dis, this.options.height * 0.5)
            this.ctx.rotate(deg * Math.PI / 180)
            this.ctx.fillText(item, 0, 0)
            this.ctx.rotate(-deg * Math.PI / 180)
            this.ctx.translate(-dis, -this.options.height * 0.5)
        })
        for (var i = 0; i < 4; i++) {
            this.ctx.strokeStyle = this.randomColor(40, 180)
            this.ctx.beginPath()
            this.ctx.moveTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height))
            this.ctx.lineTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height))
            this.ctx.stroke()
        }
        for (var i = 0; i < this.options.width / 4; i++) {
            this.ctx.fillStyle = this.randomColor(0, 255)
            this.ctx.beginPath()
            this.ctx.arc(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height), 1, 0, 2 * Math.PI)
            this.ctx.fill()
        }
    }
    validate(code) {
        var code = code.toLowerCase()
        var v_code = this.options.createCodeImg.toLowerCase()
        if (code == v_code.substring(v_code.length - 4)) {
            return true
        } else {
            return false
        }
    }
    randomNum(min, max) {
        return Math.floor(Math.random() * (max - min) + min)
    }
    randomColor(min, max) {
        let r = this.randomNum(min, max)
        let g = this.randomNum(min, max)
        let b = this.randomNum(min, max)
        return "rgb(" + r + "," + g + "," + b + ")"
    }
}

至此就成功了,拿走请扣 6,有啥问题请评论区留言

### 回答1: 微信小程序提供了canvas 2d的API接口用于动态生成二维码。首先,我们需要引入QRCode.js,一个专门用于生成二维码的JavaScript库。将此库导入小程序中,调用它提供的API,在canvas的画板上生成二维码。 首先,我们需要在wxml文件中添加canvas的画板: ```html <canvas canvas-id="qrcode" style="width: 300rpx; height: 300rpx;"></canvas> ``` 接着,在js文件中获取canvas元素: ```javascript const qrcode = wx.createCanvasContext('qrcode', this); ``` 生成我们需要的二维码: ```javascript qrcode.clearRect(0, 0, 300, 300); qrcode.drawImage("../../utils/qrcode.js", { width: 300, height: 300, text: "https://www.example.com" }) ``` 其中,第一个参数代表清除的矩形区域的左上角的 x 坐标,第二个参数代表清除的矩形区域的左上角的 y 坐标,第三个和第四个参数分别是矩形区域的宽度和高度。 以上代码通过引入QRCode.js库生成了一个链接为"https://www.example.com"的二维码,通过在canvas元素上绘制图案,最终生成了二维码。 需要注意的是,由于canvas是属于html5标签,所以相对于小程序的系统来说,属于一种比较“沉重”的浏览器标签。因此在微信小程序中,canvas的渲染性能可能会存在一些问题。因此在渲染过程中注意控制生成图片的大小和数量,尽量避免出现性能问题。 ### 回答2: 微信小程序是一款越来越受欢迎的移动应用程序,它具有非常丰富的功能。在微信小程序中,通过canvas 2d生成二维码,可以为小程序增加一些非常实用的功能。 二维码是一种十分方便的识别标志,通过扫描二维码可以快速打开某个页面或实现某种功能。在微信小程序中,通过canvas 2d可以轻松生成二维码。首先,需要引入一个QRCode.js插件,该插件可以在小程序中使用canvas 2d进行二维码的生成操作。 在引入QRCode.js之后,就可以开始进行二维码的生成了。通过使用QRCode.js提供的QRCode方法,可以生成一个二维码对象。接下来,通过canvas 2d的操作,可以将二维码对象绘制在小程序的指定位置上。 在绘制二维码时,需要注意以下几点。首先,需要设置二维码的大小和样式,包括背景颜色、前景颜色等。其次,需要将二维码进行缩放和平移操作,以便使其适应小程序的窗口大小和布局。最后,需要将绘制好的二维码输出到小程序canvas画布上,使其在小程序中显示出来。 通过canvas 2d生成二维码,可以为微信小程序增加很多强大的功能,如扫码登录、扫码支付等。这是一种非常方便有效的实现方式,也是目前越来越多小程序开发者选择的技术路线。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值