vue使用canvas生成驗證碼

components/Verification.vue

<template>
  <div>
     <el-tooltip class="item" effect="dark" content="點擊更換驗證碼" placement="right-end">
      <canvas style="cursor: pointer;" id="canvas" @click="showNum" width="138" height="36"></canvas>
    </el-tooltip>
 </div>
</template>

<script>
    export default {
      name: "Verification",
      data() {
        return {
          num: [],
          number: '',
        }
      },
      mounted(){
        this.draw(this.num);
        this.number =this.num.join().replace(/,/g,'');
      },
      methods: {
        /*點擊更換-驗證碼*/
        showNum(){
          this.draw(this.num);
          this.number =this.num.join().replace(/,/g,'');
        },
        draw(num) {
          let canvas_width=138;
          let canvas_height=36;
          let canvas =document.getElementById("canvas");//獲取到canvas的對象,演員
          let context =canvas.getContext("2d");//獲取到canvas畫圖的環境,演員表演的舞臺

          canvas.width =canvas_width;
          canvas.height =canvas_height;

          let sCode ="A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
          let aCode =sCode.split(",");
          let aLength =aCode.length;//獲取到數組的長度

          for (let i =0;i <=3;i++) {
            let j =Math.floor(Math.random() *aLength);//獲取到隨機的索引值
            let deg =Math.random() *15 *Math.PI /180;//產生0~30之間的隨機弧度
            let txt =aCode[j];//得到隨機的一個內容

            //num[i] = txt.toLowerCase(); toUpperCase()
            num[i] =txt;

            let x =20 +i *30;//文字在canvas上的x坐標
            let y =20 +Math.random() *8;//文字在canvas上的y坐標
            context.font ="bold 23px 微軟雅黑";
            context.translate(x,y);
            context.rotate(deg);
            context.fillStyle =this.randomColor();
            context.fillText(txt,0,0);
            context.rotate(-deg);
            context.translate(-x, -y);
          }
          for (let i =0;i <=5;i++) {//驗證碼上顯示線條
            context.strokeStyle =this.randomColor();
            context.beginPath();
            context.moveTo(Math.random() *canvas_width,Math.random() *canvas_height);
            context.lineTo(Math.random() *canvas_width,Math.random() *canvas_height);
            context.stroke();
          }
          for (let i =0;i <=30;i++) {//驗證碼上顯示小點
            context.strokeStyle =this.randomColor();
            context.beginPath();
            let x =Math.random() *canvas_width;
            let y =Math.random() *canvas_height;
            context.moveTo(x,y);
            context.lineTo(x +1,y +1);
            context.stroke();
          }
        },
        //得到隨機的顏色值
        randomColor() {
          let r =Math.floor(Math.random() *256);
          let g =Math.floor(Math.random() *256);
          let b =Math.floor(Math.random() *256);
          return "rgb(" +r +"," +g +"," +b +")";
        },

      }
    }
</script>

src/login/Login.vue

<template>
  <div class="login">
    <vue-particles
      color="#409EFF"
      :particleOpacity="0.7"
      :particlesNumber="60"
      shapeType="circle"
      :particleSize="6"
      linesColor="#409EFF"
      :linesWidth="1"
      :lineLinked="true"
      :lineOpacity="0.4"
      :linesDistance="150"
      :moveSpeed="3"
      :hoverEffect="true"
      hoverMode="grab"
      :clickEffect="true"
      clickMode="push"
    >
    </vue-particles>
    <div class="login-box">
      <div class="avatar"><img src="../../assets/img/img.png" alt="" /></div>
      <el-form
        :model="loginForm"
        label-position="right"
        :rules="loginRules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item label="用戶名" prop="username">
          <el-input v-model="loginForm.username" placeholder="admin"></el-input>
        </el-form-item>
        <el-form-item label="密碼" prop="password">
          <el-input
            v-model="loginForm.password"
            placeholder="123456"
          ></el-input>
        </el-form-item>
        <el-form-item label="驗證碼" prop="yzm">
          <el-row>
            <el-col :span="12"
              ><div class="grid-content bg-purple">
                <el-input
                  v-model="loginForm.yzm"
                  placeholder="請輸入驗證碼"
                ></el-input></div
            ></el-col>
            <el-col :span="12"
              ><div class="grid-content bg-purple-light" @click="yzm">
                <Verification ref="verification_code"></Verification> // 調用組件
                </div></el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登錄</el-button>
          <el-button type="info" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import Verification from "@/components/Verification"; // 引入
export default {
  name: "Login",
  components: {
    Verification // 注冊組件
  },
  data() {
    var validateusername = (rule, value, callback) => {
        if (value === ''||value===undefined) {
          callback(new Error('請輸入用戶名'));
        }  else {
          callback();
        }
      };
      var validatepassword = (rule, value, callback) => {
        if (value === ''||value===undefined) {
          callback(new Error('請輸入密碼'));
        } else {
          callback();
        }
      };
    var validateyzm = (rule, value, callback) => {
        if (value === ''||value===undefined) {
          callback(new Error('請輸入驗證碼'));
        } else if (value !== this.$refs.verification_code.number) {  // 判斷用戶輸入值是否相等
          callback(new Error('驗證碼錯誤'));
        } else {
          callback();
        }
      };
    return {
      loginForm: {
        username: "admin",
        password: "123456",
        yam: ""
      },
      loginRules: {
        username: [
          {  validator:validateusername, trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用戶名長度在3-10個字符之間",
            trigger: "blur"
          }
        ],
        password: [
          {  validator:validatepassword, trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密碼長度在6-15個字符之間",
            trigger: "blur"
          }
        ],
        yzm: [{ validator:validateyzm, trigger: "blur" }]
      }
    };
  },
  mounted() {},
  methods: {
    yzm() {
      console.log(this.$refs.verification_code.number);
    },
    reset() {
      this.$refs.ruleForm.resetFields();
    },
    login() {
      this.$refs.ruleForm.validate(valid => {
        if (valid === true) {
          window.sessionStorage.setItem("token", this.loginForm.username);
          this.$router.push("/home");
        }
      });
    }
  }
};
</script>

<style scoped>
#particles-js {
  width: 100%;
  height: calc(100% - 100px);
  position: absolute;
}
.login {
  height: 100%;
  background: -webkit-linear-gradient(top, #ababcd, white);
  background-image: url("../../assets/img/bk.jpg");
  background-size: cover;
}
.login >>> input {
  color: #61bfff;
  border: none;
  outline: none;
  -webkit-box-shadow: none;
  box-shadow: none;
  background: transparent;
}
.login-box {
  width: 450px;
  height: 400px;
  position: absolute;
  top: 50%;
  left: 50%;
  border-radius: 10px;
  transform: translate(-50%, -50%);
  background-color: #fff;
  background: -webkit-linear-gradient(220deg, rgba(53, 57, 74, 0), #000);
  background: -o-linear-gradient(220deg, rgba(53, 57, 74, 0) 0, #000 100%);
  background: linear-gradient(230deg, rgba(53, 57, 74, 0), #000);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="rgba(53, 57, 74, 0)",endColorstr="rgb(0, 0, 0)",GradientType=1);
  -webkit-box-shadow: -15px 15px 15px rgb(0 0 0 / 40%);
  box-shadow: -15px 15px 15px rgb(0 0 0 / 40%);
  -webkit-transition: all 1s;
  -o-transition: all 1s;
  transition: all 1s;
}
.avatar {
  width: 100px;
  position: absolute;
  top: -50px;
  left: 50%;
  background-color: #fff;
  transform: translateX(-50%);
  border: 1px solid #eeeeee;
  border-radius: 50%;
  height: 100px;
}
.avatar img {
  width: 100%;
  box-sizing: border-box;
  border-radius: 50%;
  padding: 5px;
}
.el-form {
  margin-top: 70px;
  padding: 0 20px 0 0;
}
</style>

最后介紹一下上面使用到的動態粒子插件屬性說明

vue-particles的屬性:
color: String類型。默認’#dedede’。粒子顏色。
particleOpacity: Number類型。默認0.7。粒子透明度。
particlesNumber: Number類型。默認80。粒子數量。
shapeType: String類型。默認’circle’。可用的粒子外觀類型有:“circle”,“edge”,“triangle”, “polygon”,“star”。
particleSize: Number類型。默認80。單個粒子大小。
linesColor: String類型。默認’#dedede’。線條顏色。
linesWidth: Number類型。默認1。線條寬度。
lineLinked: 布爾類型。默認true。連接線是否可用。
lineOpacity: Number類型。默認0.4。線條透明度。
linesDistance: Number類型。默認150。線條距離。
moveSpeed: Number類型。默認3。粒子運動速度。
hoverEffect: 布爾類型。默認true。是否有hover特效。
hoverMode: String類型。默認true。可用的hover模式有: “grab”, “repulse”, “bubble”。
clickEffect: 布爾類型。默認true。是否有click特效。
clickMode: String類型。默認true。可用的click模式有: “push”, “remove”, “repulse”, “bubble”

最后來上一個效果圖

在這里插入圖片描述
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容