# 实践-验证码

# 预览效果

点击画布重新生成验证码

# 实现代码

draw() {
    const canvasEl = document.getElementById("canvas");
    const context = canvasEl.getContext("2d");
    this.canvas_width = canvasEl.width = canvasEl.clientWidth;
    this.canvas_height = canvasEl.height = canvasEl.clientHeight;
    this.drawWord(context);
    this.drawLine(context);
    this.drawDot(context);
  },
drawWord(context) {
  // 显示四位验证码
  var strCode =
    "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
  var arrCode = strCode.split(",");
  var arrLength = arrCode.length;
  context.font = `bold ${this.canvas_height / 2}px 微软雅黑`;
  for (var i = 0; i <= 3; i++) {
    var random = Math.floor(Math.random() * arrLength);
    var deg = (Math.random() * 30 * Math.PI) / 180;
    var txt = arrCode[random];
    var x = (i * this.canvas_width) / 4;
    var y = this.canvas_height / 2 + (Math.random() * this.canvas_height) / 2;
    context.fillStyle = randomColor();
    context.translate(x, y);
    context.rotate(deg);
    context.fillText(txt, 0, 0);
    context.rotate(-deg);
    context.translate(-x, -y);
  }
},
drawLine(context) {
  //验证码上显示线条
  for (var i = 0; i <= 20; i++) {
    context.strokeStyle = randomColor();
    context.beginPath();
    let x1 = Math.random() * this.canvas_width;
    let y1 = Math.random() * this.canvas_height;
    let x2 = Math.random() * this.canvas_width;
    let y2 = Math.random() * this.canvas_height;
    let z = Math.random() * this.canvas_height;
    context.bezierCurveTo(x1, y1, (x1 + x2) / 2, z, x2, y2);
    let a1 = Math.random() * this.canvas_width;
    let a2 = Math.random() * this.canvas_height;
    let b1 = Math.random() * this.canvas_width;
    let b2 = Math.random() * this.canvas_height;
    context.moveTo(a1, a2);
    context.lineTo(b1, b2);
    context.stroke();
  }
},
drawDot(context) {
  //验证码上显示小点
  for (var i = 0; i <= 160; i++) {
    context.fillStyle = randomColor();
    context.beginPath();
    var x = Math.random() * this.canvas_width;
    var y = Math.random() * this.canvas_height;
    var r = Math.ceil(Math.random() * 5);
    context.arc(x, y, r, 0, Math.PI * 2, true);
    context.fill();
  }
}