Canvas验证码

效果展示

这里写图片描述

源码

仅供参考

this.cas = document.getElementById('codeCanvas')
let ctx = this.cas.getContext('2d')
let cwidth = this.cas.clientWidth
let cheight = this.cas.clientHeight
// 清空canvas
ctx.clearRect(0, 0, cwidth, cheight)
var Dot = function () {
  this.num = 25 // 点数
  this.hx = [] // 横座标
  this.vy = [] // 纵座标
  this.cr = [] // 半径
  this.cbgcolor = ['red', 'blue', 'gray'] // 背景色
  this.maxCr = 3 // 最大半径
}

Dot.prototype.init = function () {
  // 生成横座标
  for (var i = 0; i < this.num; i++) {
    this.hx[i] = Math.random() * cwidth
    this.vy[i] = Math.random() * cheight
    this.cr[i] = Math.random() * this.maxCr
  }
  return this
}
// 画圆点
Dot.prototype.draw = function () {
  for (var i = 0; i < this.num; i++) {
    ctx.beginPath()
    ctx.fillStyle = this.cbgcolor[Math.floor(Math.random() * this.cbgcolor.length)]
    ctx.arc(this.hx[i], this.vy[i], this.cr[i], 0, 360)
    ctx.fill()
  }
}

var Txt = function () {
  this.txt = '' // 文本内容
  this.fontSize = '20px Georgia' // 文字属性
  this.fontColor = '#333' // 文字颜色
}

Txt.prototype.draw = function (txt = this.txt) {
  ctx.font = this.fontSize
  ctx.textAlign = 'center' // 水平居中
  ctx.textBaseline = 'middle' // 垂直居中
  ctx.fillStyle = this.fontColor
  ctx.fillText(txt, cwidth / 2, cheight / 2)
}
// 生成随机数
Txt.prototype.createTxt = function () {
  for (let i = 0; i < 4; i++) {
    this.txt += Math.floor(Math.random(5) * 9 + 1)
    if (i < 4) {
      this.txt += '  '
    }
  }
  return this
}
// 创建验证码
new Dot().init().draw()
new Txt().createTxt().draw()
<canvas id="codeCanvas" width="105" height="50"></canvas>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章