canvas验证码
程序员文章站
2022-01-15 12:00:40
...
<template>
<div class="s-canvas">
<canvas
id="s-canvas"
:width="contentWidth"
:height="contentHeight"
></canvas>
</div>
</template>
<script>
export default {
name: "SIdentify",
props: {
identifyCode: {
type: String,
default: "asdf",
},
},
data() {
return {
canvas:"",
contentWidth: "100",
contentHeight: "60",
fontSize: 40,
};
},
methods: {
// 生成一个随机数
randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min);
},
// 生成一个随机的颜色
randomColor(min, max) {
let r = this.randomNum(min, max);
let g = this.randomNum(min, max);
let b = this.randomNum(min, max);
return "rgb(" + r + "," + g + "," + b + ")";
},
// 绘制code图片
drawPic() {
let canvas=this.canvas;
let ctx = canvas.getContext("2d");
ctx.clearRect(0,0,canvas.width,canvas.height);
// 绘制文字
for (let i = 0; i < this.identifyCode.length; i++) {
this.drawText(ctx, this.identifyCode[i], i);
}
},
//绘制文字
drawText(ctx, txt, i) {
ctx.fillStyle = this.randomColor(50, 160);
ctx.font =
"normal bold " +
this.randomNum(this.fontSize, this.fontSize) +
"px SimHei "; //字体大小
ctx.textBaseline = "alphabetic"; //基线对齐
let x =
(i + 1) * ((this.contentWidth - 10) / (this.identifyCode.length + 1));
let y = this.randomNum(this.fontSize, this.contentHeight - 5);
var deg = this.randomNum(-45, 45);
// 修改坐标原点和旋转角度
ctx.translate(x, y); //移动不同位置 参数偏移量
ctx.rotate((deg * Math.PI) / 180); //旋转 参数角度
ctx.fillText(txt, 0, 0);
// 恢复坐标原点和旋转角度
ctx.rotate((-deg * Math.PI) / 180);
ctx.translate(-x, -y);
},
},
watch: {
identifyCode() {
this.drawPic();
},
},
mounted() {
this.$nextTick(() => {
this.canvas = document.getElementById("s-canvas");
this.drawPic();
});
},
};
</script>
生成4位雅正吗
// 获取验证码
getCode(){
var strArr = [0,1,2,3,4,5,6,7,8,9];
for(var i=0;i<26;i++) {
strArr.push(String.fromCharCode(97+i)); // String.fromCharCode()方法
strArr.push(String.fromCharCode(65+i)); //fromCharCode() 可接受一个指定的 Unicode 值,然后返回一个字符串。
}
var newArr = [];
for(var j = 0;j < 4; j++){
var a = Math.floor(Math.random()*strArr.length);
newArr.push(strArr[a]);
}
this.imgCode=newArr.join("");
},
上一篇: 时间线效果
下一篇: JDK8新特性——Optional工具类