封装为一个函数
创建verificationCode.js文件
// 生成指定区域内的数字
const getRandomNumber = (min, max) => {
return parseInt(Math.random() * (max - min) + min);
};
// 生成随机颜色
const getRandomColor = (min = 0, max = 255) => {
let [r, g, b] = [getRandomNumber(min, max), getRandomNumber(min, max), getRandomNumber(min, max)];
return `rgb(${r},${g},${b})`;
};
// 生成随机的字体大小
const getRandomFontSize = (min = 0, max = 255, fontType = 'Simhei') => {
return `${getRandomNumber(min, max)}px ${fontType}`;
};
// 生成随机的字体大小
export const createVerificationCode = (ctx, XLength, YLength, code) => {
ctx.fillStyle = getRandomColor(210, 230); //背景的填充颜色
ctx.fillRect(0, 0, XLength, YLength); //fillRect() 是Canvas 2D API 绘制填充矩形的方法
// 开始绘制字符串
code.split('').forEach((element, index) => {
ctx.font = getRandomFontSize(15, 22); // 设置字体及大小
ctx.textBaseline = 'top'; // 决定文字垂直方向的对齐方式
ctx.fillStyle = getRandomColor(80, 150); // 设置文字的填充颜色
ctx.save(); // 过将当前状态放入栈中,保存 canvas 全部状态的方法。
ctx.translate(index * 15 + 5, getRandomNumber(10,25)); // 将 canvas 按原始 x点的水平方向、原始的 y点垂直方向进行平移变换
ctx.rotate((getRandomNumber(-30, 30) * Math.PI) / 180); // 在变换矩阵中增加旋转的方法
ctx.fillText(element, 0, 0); // 填充文本
ctx.restore(); //通过在绘图状态栈中弹出顶端的状态,将 canvas 恢复到最近的保存状态的方法。 如果没有保存状态,此方法不做任何改变。
});
// 随机生成干扰线
for (let i = 0; i < 6; i++) {
ctx.beginPath(); // 通过清空子路径列表开始一个新路径的方法
ctx.strokeStyle = getRandomColor(180, 210);
ctx.moveTo(getRandomNumber(0, XLength), getRandomNumber(0, YLength)); // 将一个新的子路径的起始点移动到(x,y)坐标的方法。
ctx.lineTo(getRandomNumber(0, XLength), getRandomNumber(0, YLength)); // 使用直线连接子路径的终点到x,y坐标的方法(并不会真正地绘制)
ctx.closePath();
ctx.stroke();
}
// 随机生成干扰圆点
for (let i = 0; i < 40; i++) {
ctx.beginPath(); // 通过清空子路径列表开始一个新路径的方法
// 绘制圆弧路径
ctx.arc(getRandomNumber(0, XLength), getRandomNumber(0, YLength), 1, 0, 2 * Math.PI);
ctx.closePath();
ctx.fillStyle = getRandomColor(150, 200);
ctx.fill();
}
};
调用
<template>
<canvas style="position: absolute" ref="canvas" width="100" height="40"></canvas>
</template>
<script>
import { createVerificationCode } from '@/utils/verificationCode.js';
export default {
name: 'VerificationCode',
props: ['verificationCode'],
watch: {
verificationCode: {
handler: function (newCode, oldCode) {
const canvas = this.$refs.canvas;
const XLength = 100 // 指定宽度
const YLength = 40 // 指定高度
const ctx = canvas.getContext('2d');
createVerificationCode(ctx, XLength, YLength, newCode);
}
}
}
};
</script>
<style></style>