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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章