react canvas 生成验证码

import React from 'react';
class Code extends React.Component{
    state = {
        code: ''         //验证码
    }
    componentDidMount () {
        this.createCode()
    }
    randomNum=(min, max)=>{
      return Math.floor(Math.random() * (max - min) + min);
    }
    createCode = () => {
        const ctx = this.canvas.getContext('2d')
        const chars = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
        let code = ''
        ctx.clearRect(0, 0, 80, 39)
        for (let i = 0; i < 4; i++) {
          const char = chars[this.randomNum(0, 57)]
          code += char
          ctx.font = randomNum(20, 25) + 'px'
          ctx.fillStyle = '#D3D7F7'
          ctx.textBaseline = 'middle'
          ctx.shadowOffsetX = this.randomNum(-3, 3)
          ctx.shadowOffsetY = this.randomNum(-3, 3)
          ctx.shadowBlur = this.randomNum(-3, 3)
          ctx.shadowColor = 'rgba(0, 0, 0, 0.3)'
          let x = 80 / 5 * (i + 1)
          let y = 39 / 2
          let deg = this.randomNum(-25, 25)
          ctx.translate(x, y)
          ctx.rotate(deg * Math.PI / 180)
          ctx.fillText(char, 0, 0)
          ctx.rotate(-deg * Math.PI / 180)
          ctx.translate(-x, -y)
        }
        this.setState({
          code
        })
    }
    render(){
        return(
            <div><canvas onClick={this.createCode} width="80" height='39' ref={el => this.canvas = el}/></div>
        )
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不再重要

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值