用canvas生成验证码
2018-04-12 本文已影响0人
余尧鸟
function () {
this.options.code = ''
var canvas = document.getElementById(this.options.canvasId)
if (canvas.getContext) {
var ctx = canvas.getContext('2d')
} else {
return
}
ctx.textBaseline = 'middle'
ctx.fillStyle = this.randomColor(180, 240)
ctx.fillRect(0, 0, this.options.width, this.options.height)
var txtArr = ''
if (this.options.type === 'blend') {
txtArr = this.options.numArr.concat(this.options.letterArr)
} else if (this.options.type === 'number') {
txtArr = this.options.numArr
} else {
txtArr = this.options.letterArr
}
for (var i = 1; i <= 4; i++) {
var txt = txtArr[this.randomNum(0, txtArr.length)]
this.options.code += txt
ctx.font = this.randomNum(this.options.height / 2, this.options.height) + 'px SimHei'
ctx.fillStyle = this.randomColor(50, 160)
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)'
var x = this.options.width / 5 * i
var y = this.options.height / 2
var deg = this.randomNum(-30, 30) /** 设置旋转角度和坐标原点**/
ctx.translate(x, y)
ctx.rotate(deg * Math.PI / 180)
ctx.fillText(txt, 0, 0) /** 恢复旋转角度和坐标原点**/
ctx.rotate(-deg * Math.PI / 180)
ctx.translate(-x, -y)
}
/** 绘制干扰线**/
for (var LT = 0; LT < 4; LT++) {
ctx.strokeStyle = this.randomColor(40, 180)
ctx.beginPath()
ctx.moveTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height))
ctx.lineTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height))
ctx.stroke()
}
/** 绘制干扰点**/
for (var FL = 0; FL < this.options.width / 40; FL++) {
ctx.fillStyle = this.randomColor(0, 255)
ctx.beginPath()
ctx.arc(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height), 1, 0, 2 * Math.PI)
ctx.fill()
}
},