canvas随机数字验证码
时间: 2023-08-03 20:15:11 浏览: 50
生成随机数字验证码可以使用canvas来实现。以下是一个简单的示例代码:
HTML代码:
```html
<canvas id="captcha" width="120" height="40"></canvas>
<button onclick="generate()">生成验证码</button>
```
JavaScript代码:
```javascript
function generate() {
var canvas = document.getElementById('captcha');
var ctx = canvas.getContext('2d');
// 绘制背景
ctx.fillStyle = '#EEE';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制随机数字
var code = '';
for (var i = 0; i < 4; i++) {
var num = Math.floor(Math.random() * 10);
code += num;
ctx.fillStyle = '#333';
ctx.font = 'bold 24px Arial';
ctx.fillText(num, i * 30 + 10, 30);
}
// 绘制干扰线
for (var i = 0; i < 5; i++) {
ctx.strokeStyle = '#999';
ctx.beginPath();
ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.stroke();
}
return code;
}
```
这段代码会在canvas上生成一个随机的四位数字验证码,并返回验证码的值。同时,还会在画布上绘制一些干扰线,增加验证码的安全性。