JS验证码生成(入门级别)

练手项目:JavaScript验证码

 1 <!DOCTYPE html>
 2 <html>
 3 
 4     <head>
 5         <meta charset="UTF-8">
 6         <title></title>
 7         <style>
 8             #mycanvas {
 9                 cursor: pointer;
10             }
11         </style>
12     </head>
13 <!--值得优化的地方:①干扰线的随机颜色;②可以加点干扰点-->
14     <body>
15         <canvas id="mycanvas" width='90' height='40'>
16             您的浏览器不支持canvas,请换个浏览器试试~
17         </canvas>
18     </body>
19 
20     <script>
21         /*生成4位随机数*/
22         function rand() {
23             var str = "abcdefghijklmnopqrstuvwxyz0123456789";
24             var arr = str.split("");
25             var validate = "";
26             var ranNum;
27             for(var i = 0; i < 4; i++) {
28                 ranNum = Math.floor(Math.random() * 36); //随机数在[0,35]之间
29                 validate += arr[ranNum];
30             }
31             return validate;
32         }
33 
34         /*干扰线的随机x坐标值*/
35         function lineX() {
36             var ranLineX = Math.floor(Math.random() * 90);
37             return ranLineX;
38         }
39 
40         /*干扰线的随机y坐标值*/
41         function lineY() {
42             var ranLineY = Math.floor(Math.random() * 40);
43             return ranLineY;
44         }
45 
46         function clickChange() {
47             var mycanvas = document.getElementById('mycanvas');
48             var cxt = mycanvas.getContext('2d');
49             cxt.fillStyle = '#000';
50             cxt.fillRect(0, 0, 90, 40);
51 
52             /*生成干扰线20条*/
53             for(var j = 0; j < 30; j++) {
54                 cxt.strokeStyle = '#fff';
55                 cxt.beginPath(); //若省略beginPath,则每点击一次验证码会累积干扰线的条数
56                 cxt.moveTo(lineX(), lineY());
57                 cxt.lineTo(lineX(), lineY());
58                 cxt.lineWidth = 0.5;
59                 cxt.closePath();
60                 cxt.stroke();
61             }
62 
63             cxt.fillStyle = 'yellow';
64             cxt.font = 'bold 20px Arial';
65             cxt.fillText(rand(), 30, 30); //把rand()生成的随机数文本填充到canvas中      
66         }
67 
68         clickChange();
69 
70         /*点击验证码更换*/
71         mycanvas.onclick = function(e) {
72             e.preventDefault(); //阻止鼠标点击发生默认的行为
73             clickChange();
74         };
75     </script>
76 
77 </html>

结果显示截图:

原文地址:https://www.cnblogs.com/superdrew/p/9141343.html