- READ and UNDERSTAND the code, detailed explainations are provided in comments. Also, check the reference links below
- TWEAK the settings (font style, color, translate pos, rotation, scale) to however you want them to be if needed
- HAVE FUN playing with the code, they are ALIVE!
使用代码前,推荐先做以下几件事:
- 读懂代码。源码中有详细的注释说明(英文),或者阅读 我的解读文章(中文) 及参考最下方的 References
- 调整源码中对字体、颜色、位移、旋转、缩放的设置,以切合自己的需求
- 代码是活的,享受每一次尝试的过程
- Copy
canvas-verification-code.js
andcodeBg.png
to your repo. - Make sure your project has a es6 compiler (e.g.: Babel) to compile the code
使用方法:
- 把
canvas-verification-code.js
andcodeBg.png
复制到项目下 - 项目中需要有可以把 es6 编译为 es5 的工具,例如 Babel
See it live on CODEPEN
<div class='verificationCode'>
<!-- use css absolute positioning to put codeBg.png
underneath your verification code -->
<div class='codeBackground'></div>
<img class='codeImage' src='' alt='verificationCode' />
</div>
<!-- ... ... -->
<script src='/path/to/canvas-verification-code.js'>
<script>
var verificationCode = generateCode(120, 40)
var codeImage = document.getElementsByClassName('codeImage')[0]
codeImage.src = verificationCode.data
</script>
See it live on CODEPEN
<template lang='pug'>
div(id='app' class='verificationCode')
//- use css absolute positioning to put codeBg.png
//- underneath your verification code
div(class='codeBackground')
img(
class='codeImage'
:src='imageData'
alt='verificationCode'
)
br
input(v-model='codeInput' placeholder="enter code")
p code input is: {{ validInput }}
</template>
import generateCode from '/path/to/canvas-verification-code.js'
export default {
data() {
return {
codeInput: '',
imageData: '',
codeText : '',
}
},
computed: {
validInput() {
return this.codeText === this.codeInput
? 'correct'
: 'not correct'
}
},
mounted() {
const { code, data } = generateCode(120, 40)
this.imageData = data
this.codeText = code
}
}
name | type | required | meaning | default | options |
---|---|---|---|---|---|
width | number | true | width of canvas background | ||
height | number | true | height of canvas background | ||
type | string | false | type of code characters | "default" (mix of letter and number) |
"letter", "number" |
codeLen | number | false | length of code characters | 4 | positive integers |
[2] Generating random whole numbers in JavaScript in a specific range?
[4] html5 Canvas画图教程26:用transform来实现位移,缩放,旋转等
[5] shoestrong/validate-code-canvas
[6] KIDx/verify-code