<template>
<canvas ref="canvas" class="canvas" :width="state.contentWidth" :height="state.contentHeight"
@click="changeCanvasVal"></canvas>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, watch, defineEmits } from "vue";
const canvas = ref();
const state = reactive({
contentWidth: 80,
contentHeight: 38,
valicodes: "1234567890", // 数字
identifyCode: "", //储存生成验证码
count: 4, //个数
});
onMounted(() => {
state.identifyCode = draw();
});
const emit = defineEmits(['identifyCodeValue', ]) //子组件给父组件传值
watch(() => state.identifyCode, (newVal, oldValue) => {
emit('identifyCodeValue', newVal)
})
// watch(() => {
// return state.identifyCode;
// },
// (newval, oldval) => {
// console.log(newval, 'newval');
// }
// );
//随机数
const randomNum = (min: any, max: any) => {
return Math.floor(Math.random() * (max - min) + min);
};
//开始绘制
const draw = () => {
const ctx = canvas.value.getContext("2d");
ctx.rect(30, 30, 20, 20);
ctx.stroke();
ctx.fillStyle = '#fff'; //绘制背景
ctx.lineWidth = 1; //绘制背景
ctx.strokeStyle = "blue";
ctx.beginPath(); // 开始绘制边框
ctx.fillRect(0, 0, state.contentWidth, state.contentHeight);
// 绘制文字
let identifyCode = "";
for (let i = 0; i < state.count; i++) {
//控制字数
const text = state.valicodes[randomNum(0, state.valicodes.length - 1)];
identifyCode += text;
ctx.font = 16 + "px Arial"; //字体大小
ctx.fillStyle = '#606266'; //字体颜色
ctx.textBaseline = "middle";
ctx.save();
//文字依次随机的上下左右
let x = (state.contentWidth / state.count) * i + 5;
let y = (2)
ctx.translate(x, y);
ctx.fillText(text, 0, state.contentHeight / 2); //左
ctx.restore();
}
return identifyCode;
};
const changeCanvasVal = () => {
state.identifyCode = draw();
};
</script>
<style lang="scss">
.canvas {
padding: 0 15px;
border: 1px solid #d3d3d3;
border-radius: 5px;
}
</style>
canvas随机数字验证码
最新推荐文章于 2024-05-09 06:32:10 发布