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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值