<template>
<canvas
ref="canvas"
:width="state.contentWidth"
:height="state.contentHeight"
@click="changeCanvasVal"
></canvas>
</template>
<script setup>
import { reactive, ref, onMounted, watch } from "vue";
const canvas = ref();
const state = reactive({
contentWidth: 210,
contentHeight: 50,
valicodes: "abcdefghijklmnopqrstuvwxyz1234567890",
identifyCode: "",
count: 6, //个数
});
onMounted(() => {
state.identifyCode = draw();
console.log(state.identifyCode);
});
watch(
() => {
return state.identifyCode;
},
(newval, oldval) => {
console.log(newval);
}
);
//随机数
const randomNum = (min, max) => {
return Math.floor(Math.random() * (max - min) + min);
};
//随机颜色
const randomColor = (min, max) => {
let r = randomNum(min, max);
let g = randomNum(min, max);
let b = randomNum(min, max);
return `rgb(${r},${g},${b})`;
};
//干扰线
const drawLine = (ctx) => {
for (let i = 0; i < 5; i++) {
//5条线
ctx.strokeStyle = randomColor(40, 180);
ctx.beginPath();
ctx.moveTo(
randomNum(0, state.contentWidth),
randomNum(0, state.contentHeight)
);
ctx.lineTo(
randomNum(0, state.contentWidth),
randomNum(0, state.contentHeight)
);
ctx.stroke();
}
};
//绘制点
const drawDot = (ctx) => {
for (let i = 0; i < 20; i++) {
//20个点
ctx.fillStyle = randomColor(0, 255);
ctx.beginPath();
ctx.arc(
randomNum(0, state.contentWidth),
randomNum(0, state.contentHeight),
1,
0,
2 * Math.PI
);
ctx.fill();
}
};
//开始绘制
const draw = () => {
const ctx = canvas.value.getContext("2d");
//绘制背景
ctx.fillStyle = randomColor(220, 255);
ctx.fillRect(0, 0, state.contentWidth, state.contentHeight);
// 绘制文字
let identifyCode = "";
for (let i = 0; i < state.count; i++) {
//控制字数
// drawText(ctx, state.identifyCode[i], i);
const text = state.valicodes[randomNum(0, state.valicodes.length - 1)];
identifyCode += text;
// 字体随机的旋转角度
var deg = randomNum(-10, 10);
ctx.font = randomNum(18, 40) + "px Arial"; //字体大小
ctx.fillStyle = randomColor(50, 160); //字体颜色
ctx.textBaseline = "middle";
ctx.save();
//文字依次随机的上下左右
let x = (state.contentWidth / state.count) * i + 10;
let y = randomNum(
-state.contentHeight / state.count,
state.contentHeight / state.count
);
ctx.translate(x, y);
ctx.rotate((deg * Math.PI) / 180); //文字旋转角度
ctx.fillText(text, 0, state.contentHeight / 2);
ctx.restore();
}
//绘制线条
drawLine(ctx);
//绘制点
drawDot(ctx);
return identifyCode;
};
const changeCanvasVal = () => {
state.identifyCode = draw();
};
</script>
<style lang="scss"></style>
vue3+canvas实现数字验证码
最新推荐文章于 2024-09-10 13:51:16 发布