使用canvas生成图片验证码

效果图:

点击图片也会刷新图片

代码:index.js

import React, { Component } from 'react'

import styles from './index.less';

class First extends Component {

constructor(props) {

super(props)

this.state = {

code: ''

}

}

componentDidMount() {

this.createCode()

}

createCode = () => {

//定义验证码的宽高,干扰点数量,干扰线数量

const width = 100

const height = 60

const points = 50

const line = 4

//生成随机数

function randomNum(min, max) {

return Math.floor(Math.random() * (max - min) + min);

}

//随机颜色

function randomColor(min, max) {

var r = randomNum(min, max);

var g = randomNum(min, max);

var b = randomNum(min, max);

return `rgb(${r},${g},${b})`;

}

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, width, height)

// 绘制四个验证数码

for (let i = 0; i < 4; i++) {

const char = chars[randomNum(0, 57)]

code += char

ctx.font = randomNum(20, 25) + 'px SimHei' //设置字体随机大小

ctx.fillStyle = randomColor(0, 255) //设置字体随机颜色

ctx.textBaseline = 'middle'

ctx.shadowOffsetX = randomNum(-3, 3)

ctx.shadowOffsetY = randomNum(-3, 3)

ctx.shadowBlur = randomNum(-3, 3)

ctx.shadowColor = 'rgba(0, 0, 0, 0.3)'

let x = width / 5 * (i + 1)

let y = height / 2

let deg = 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)

}

//绘制干扰线

for (var i = 0; i < line; i++) {

ctx.strokeStyle = randomColor(0, 255);

ctx.beginPath();

ctx.moveTo(randomNum(0, width), randomNum(0, height));

ctx.lineTo(randomNum(0, width), randomNum(0, height));

ctx.stroke();

}

//绘制干扰点

for (var i = 0; i < points; i++) {

ctx.fillStyle = randomColor(0, 255);

ctx.beginPath();

ctx.arc(randomNum(0, width), randomNum(0, height), 1, 0, 2 * Math.PI);

ctx.fill();

}

this.setState({

code

})

}

render() {

return (

<div className={styles.imageCodeWrapper}>

<div className={styles.canvas}>

<canvas onClick={this.createCode} width="100" height='60' ref={el => this.canvas = el} />

</div>

</div>

)

}

}

export default First

index.less

.canvas{

background-color: rgba(0, 0, 0, 0.1);

height: 60px;

width: 100px;

display: inline-block;

}

-------------------------------------------------------------------------------------------------------------------------------------------------------------------如遇到问题:+WX:WAZJ-0508,及时联系---------------------------------------------------------------------------------------------------------------------------------------------------

发布了58 篇原创文章 · 获赞 41 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/Zeng__Yi/article/details/90515570