canvas随机数字验证码
时间: 2023-08-03 11:19:08 浏览: 30
以下是一个基于 Canvas 的随机数字验证码的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Canvas Random Number Captcha</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="captcha" width="120" height="40"></canvas>
<br>
<button onclick="generateCaptcha()">Generate Captcha</button>
<script>
function generateCaptcha() {
var canvas = document.getElementById("captcha");
var ctx = canvas.getContext("2d");
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw random numbers
var num1 = Math.floor(Math.random() * 10);
var num2 = Math.floor(Math.random() * 10);
var num3 = Math.floor(Math.random() * 10);
var num4 = Math.floor(Math.random() * 10);
ctx.font = "20px Arial";
ctx.fillText(num1, 10, 25);
ctx.fillText(num2, 40, 25);
ctx.fillText(num3, 70, 25);
ctx.fillText(num4, 100, 25);
// Draw random lines
ctx.beginPath();
for (var i = 0; i < 5; i++) {
var x1 = Math.random() * canvas.width;
var y1 = Math.random() * canvas.height;
var x2 = Math.random() * canvas.width;
var y2 = Math.random() * canvas.height;
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
ctx.stroke();
}
</script>
</body>
</html>
```
这个示例代码随机生成了四个数字和五条线作为验证码,可以通过点击 "Generate Captcha" 按钮来生成新的验证码。你也可以根据自己的需求进行修改和定制。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)