天天看點

vue 使用canvas生成含幹擾線的驗證碼

效果圖:

vue 使用canvas生成含幹擾線的驗證碼

.ts

mounted() {
    this.createCode();
  }

  private rand() {
    let str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let arr = str.split("");
    let ranNum = Math.floor(Math.random() * 36);
    let randomCode = arr[ranNum];
    return randomCode;
  }

  private drawline(canvas, context) {
    context.beginPath();
    context.moveTo(
      Math.floor(Math.random() * (this as any).canvasWidth),
      Math.floor(Math.random() * (this as any).canvasHeight)
    );
    context.lineTo(
      Math.floor(Math.random() * (this as any).canvasWidth),
      Math.floor(Math.random() * (this as any).canvasHeight)
    );
    context.lineWidth = 1;
    context.strokeStyle = "#275DB3";  // 幹擾線條的顔色
    context.stroke();
  }

  private createCode() {
    let code = "";
    let myCanvas = this.$refs.mycanvas as IndexObject;
    let context = myCanvas.getContext("2d");
    context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
    context.strokeStyle = "#FFF";  // 邊框的顔色
    // context.fillStyle="red"; 字型的顔色
    context.strokeRect(0, 0, this.canvasWidth, this.canvasHeight);
    for (let i = 0; i < 20; i++) {
      this.drawline(myCanvas, context);
    }
    for (let k = 0; k < 4; k++) {
      context.font = "20px Arial";
      context.save();
      let rA = 1 - Math.random() * 2;
      let angle = rA / 8;
      let ranNum = this.rand();
      context.rotate(angle);
      context.fillText(ranNum, 18 * k + 4, 25);
      context.restore();
      code += ranNum;
    }
    this.verificationCode = code;
  }

比較:if (this.confirmCode.toUpperCase() !== this.verificationCode) {
      console.log("驗證碼輸入錯誤!");
    }
           

.vue

<canvas
            ref="mycanvas"
            id="mycanvas"
            style="margin-left:10px"
            :width="canvasWidth"
            :height="canvasHeight"
            @click="createCode"
          ></canvas>