利用canvas绘制登录前的验证码
Vue
<canvas @click="createCode" width="80" height='40' id='myCanvas'/>
mounted () {
//该方法需要节点加载完成之后进行,所以需放再mounted阶段执行
this.createCode()
},
methods:{
//绘制验证码主要方法
createCode(){
let dot = document.getElementById("myCanvas")
const ctx = dot.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 = this.randomNum(20, 25) + 'px SimHei'
/**随机字体颜色**/
ctx.fillStyle = 'rgb('+this.randomNum(0, 255)+','+this.randomNum(0, 255)+','+this.randomNum(0, 255)+')'
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)
}
//随机数控制
randomNum(min,max){
return Math.floor(Math.random() * (max - min) + min);
},
}
react
componentDidMount () {
this.createCode()
}
/**
* 生成验证码
*/
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 = this.randomNum(20, 25) + 'px SimHei' //设置字体随机大小
ctx.fillStyle = '#000'
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
})
}
同一函数组件下:
<canvas onClick={this.createCode} width="80" height='39' ref={el => this.canvas = el}/>