您好,登錄后才能下訂單哦!
怎么在vue中封裝一個隨機驗證碼組件?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
<template> <div > <canvas :width="contentWidth" :height="contentHeight" id="cav" @click="next()"></canvas> </div> </template> <script> // import num from './components/cc' export default { name: 'verificationCode', props: { fontSize: { type: Number, default: 20 }, contentWidth: { type: Number, default: 100 }, contentHeight: { type: Number, default: 40 }, verification: { type: String }, refreshCode: { type: Boolean } }, watch: { verification: function (newVal) { if (newVal.toLowerCase() === this.identify.toLowerCase()) { this.$emit('handleIdentify', true) } else { this.$emit('handleIdentify', false) } }, refreshCode: function (newVal) { this.draw() } }, mounted () { this.draw() }, data () { return { identify: '', letter: [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'] } }, methods: { draw () { let self = this let text = this.randomNum() this.identify = text.join('') let ctx = document.getElementById('cav') let cav = ctx.getContext('2d') cav.clearRect(0, 0, self.contentWidth, self.contentHeight) let w = ctx.width let h = ctx.height cav.textBaseline = 'bottom' self.drawText(cav, text[0], 10, 10, self.randomDeg(0, 0.1), 20) self.drawText(cav, text[1], 20, 10, self.randomDeg(0, 0.1)) self.drawText(cav, text[2], 25, 10, self.randomDeg(0, 0.1)) self.drawText(cav, text[3], 30, 10, self.randomDeg(0, 0.1)) let i for (i = 0; i < 3; i++) { self.drawLine(cav, self.randomDeg(0, 0.3 * w, 1), self.randomDeg(0, h, 1), self.randomDeg(0, w, 1), self.randomDeg(0, h, 1), self.randomDeg(0.8 * w, w, 1), self.randomDeg(0, h, 1)) } }, drawText (cav, text, x1, y1, route) { cav.beginPath() cav.fillStyle = '#ffe9db' cav.font = this.fontSize + 'px' + ' ' + '黑體' cav.translate(x1, y1) cav.rotate(Math.PI * route) cav.fillText(text, x1, y1) cav.fill() cav.rotate(-Math.PI * route) cav.translate(-(x1), -(y1)) }, drawLine (cav, x1, y1, x2, y2, x3, y3) { cav.beginPath() cav.strokeStyle = 'rgb(155, 204, 237)' cav.bezierCurveTo(x1, y1, x2, y2, x3, y3) cav.stroke() }, randomNum () { // 生成隨機字 let i let letter = this.letter let text = [] for (i = 0; i < 4; i++) { text.push(letter[Math.floor(Math.random() * 36)]) } return text }, randomDeg (min, max, f) { // 設置文字傾斜角度 f = undefined ? Math.random() > 0.5 ? 1 : -1 : 1 return f * (Math.random() * (max - min) + min) }, next () { this.draw() } } } </script> <style scoped> </style>
樣式什么的自己可以調一調,效果如下:
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。