接上一篇生成验证码文章,经修改生成了一个简单验证码,供大家参考
identify.vue组件(主要用于定义参数和方法)
<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: '1234'
},
fontSizeMin: {
type: Number,
default: 16
},
fontSizeMax: {
type: Number,
default: 40
},
backgroundColorMin: {
type: Number,
default: 180
},
backgroundColorMax: {
type: Number,
default: 240
},
colorMin: {
type: Number,
default: 50
},
colorMax: {
type: Number,
default: 160
},
lineColorMin: {
type: Number,
default: 40
},
lineColorMax: {
type: Number,
default: 180
},
dotColorMin: {
type: Number,
default: 0
},
dotColorMax: {
type: Number,
default: 255
},
contentWidth: {
type: Number,
default: 80
},
contentHeight: {
type: Number,
default: 38
}
},
methods: {
// 生成一个随机数
randomNum (min, max) {
return Math.floor(Math.random() * (max - min) + min)
},
drawPic () {
const canvas = document.getElementById('s-canvas')
const ctx = canvas.getContext('2d')
ctx.textBaseline = 'bottom'
// 绘制背景
ctx.fillStyle = 'rgb(174,201,230)'
ctx.fillRect(0, 0, this.contentWidth, this.contentHeight)
// 绘制文字
for (let i = 0; i < this.identifyCode.length; i++) {
this.drawText(ctx, this.identifyCode[i], i)
}
},
drawText (ctx, txt, i) {
ctx.fillStyle = 'rgb(51,51,103)'
ctx.font = '18px SimHei'
const x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))
// 修改坐标原点和旋转角度
ctx.translate(x, 30)
ctx.fillText(txt, 0, 0)
// 恢复坐标原点和旋转角度
ctx.translate(-x, -30)
}
},
watch: {
identifyCode () {
this.drawPic()
}
},
mounted () {
this.drawPic()
}
}
</script>
在 main.js进行引入(注意路径的地址):
import SIdentify from './components/page/identify'
Vue.component('s-identify', SIdentify)
test.vue(在页面进行使用):
<template>
<div class="code" @click="refreshCode">
<s-identify :identifyCode="identifyCode"></s-identify>
</div>
</template>
<script>
export default {
data() {
return {
identifyCodes: '1234567890abcdefg',
identifyCode: ''
}
},
mounted() {
this.identifyCode = ''
this.makeCode(this.identifyCodes, 4)
},
methods: {
randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min)
},
refreshCode() {
this.identifyCode = ''
this.makeCode(this.identifyCodes, 4)
},
makeCode(o, l) {
for (let i = 0; i < l; i++) {
this.identifyCode += this.identifyCodes[
this.randomNum(0, this.identifyCodes.length)
]
}
console.log(this.identifyCode)
}
}
}
</script>
<style>
.code {
margin: 50px auto;
width: 114px;
height: 40px;
/*border: 1px solid red;*/
}
</style>