组件代码如下:
<template>
<div style="cursor: pointer;" @click="changeCode">
<canvas id="identify" :width="width" :height="height"></canvas>
</div>
</template>
<script>
export default {
name: 'SIdentify',
props: {
// 字体最小值
fontSizeMin: {
type: Number,
default: 20
},
// 字体最大值
fontSizeMax: {
type: Number,
default: 20
},
//容器宽度
width: {
type: Number,
default: 100
},
//容器高度
height: {
type: Number,
default: 28
}
},
data() {
return {
code: ""
}
},
methods: {
randomCode(length) {
let str = ''
const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
]
for (let i = 0; i < length; i++) {
let pos = Math.round(Math.random() * (arr.length - 1))
str += arr[pos]
}
this.code = str;
},
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 + ')'
},
drawImg() {
let canvas = document.getElementById('identify')
let ctx = canvas.getContext('2d')
ctx.textBaseline = 'bottom'
ctx.fillStyle = "rgb(255,255,255)";
ctx.strokeStyle = "#FFFFFF";
ctx.fillRect(0, 0, this.width, this.height);
this.randomCode(4);
for (let i = 0; i < this.code.length; i++) {
this.drawFont(ctx, this.code[i], i)
}
},
drawFont(ctx, txt, i) {
ctx.fillStyle = this.randomColor(50, 160);
ctx.font = this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei';
let x = (i + 1) * (this.width / (this.code.length + 1));
let y = this.randomNum(this.fontSizeMax, this.height - 5);
var deg = this.randomNum(-30, 30);
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)
},
changeCode() {
this.drawImg();
this.$emit('changeCode', this.code);
}
},
mounted() {
this.drawImg()
}
}
</script>