在 OpenHarmony(基于 ArkTS / eTS 开发)中,生成验证码通常有两种常见方式:
适用于登录、注册等不需要服务器校验的场景。
// VerificationCode.ets
import canvas from '@ohos.graphics.canvas'
@Entry
@Component
struct VerificationCode {
private code: string = ''
private canvasRef: CanvasRenderingContext2D | null = null
aboutToAppear() {
this.refreshCode()
}
// 生成随机验证码
generateCode(length: number = 4): string {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
let result = ''
for (let i = 0; i < length; i++) {
result += chars[Math.floor(Math.random() * chars.length)]
}
return result
}
// 绘制验证码
drawCode() {
if (!this.canvasRef) return
const ctx = this.canvasRef
ctx.clearRect(0, 0, 200, 80)
// 背景
ctx.fillStyle = '#f2f2f2'
ctx.fillRect(0, 0, 200, 80)
// 文字
ctx.font = '40px sans-serif'
for (let i = 0; i < this.code.length; i++) {
ctx.fillStyle = this.randomColor()
ctx.fillText(this.code[i], 30 + i * 40, 55)
}
// 干扰线
for (let i = 0; i < 5; i++) {
ctx.strokeStyle = this.randomColor()
ctx.beginPath()
ctx.moveTo(Math.random() * 200, Math.random() * 80)
ctx.lineTo(Math.random() * 200, Math.random() * 80)
ctx.stroke()
}
}
randomColor(): string {
const r = Math.floor(Math.random() * 256)
const g = Math.floor(Math.random() * 256)
const b = Math.floor(Math.random() * 256)
return `rgb(${r},${g},${b})`
}
refreshCode() {
this.code = this.generateCode()
this.drawCode()
}
build() {
Column() {
Canvas(this.canvasRef)
.width(200)
.height(80)
.onClick(() => this.refreshCode())
Button('刷新验证码')
.onClick(() => this.refreshCode())
}
}
}
✅ 特点:
适用于防止机器刷接口。
GET /api/captcha
Response:
{
"captchaId": "abc123",
"imageBase64": "data:image/png;base64,..."
}
前端:
Image(this.imageBase64)
// 获取短信验证码
Button('获取验证码')
.onClick(async () => {
await httpRequest.post('/api/sms/send', {
phone: '13800000000'
})
})
后端负责:
| 场景 | 推荐方式 |
|---|---|
| 内部管理页面 | 前端 Canvas |
| 用户登录 | 后端图片验证码 |
| 注册 / 改密 | 短信 / 邮箱验证码 |
如果你需要:
可以告诉我你的具体版本和场景,我可以直接帮你写完整代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。