利用纯JS和HTML Canvas生成随机迷宫过程中产生的有趣的事情

上效果图:
#先看生成随机迷宫的代码吧↓
 1 <html>
 2 <head>
 3 <title>生成随机迷宫v1.0</title>
 4 </head>
 5 <body>
 6 <center style="margin-top: 20px;">
 7     <canvas id="myCan1" title="作者:谢辉"></canvas>
 8     <p>生成随机迷宫v1.0</p>
 9     <button onclick="history.go(0);">刷新</button>
10 </center>
11 </body>
12 <script>
13 var width = 1600;
14 var height = 800;
15 var cellWidth = 40;
16 var canvas = document.getElementById("myCan1");
17 var cxt = canvas.getContext("2d");
18 // 初始化canvas容器
19 function initCanvas() {
20     canvas.width = width;
21     canvas.height = height;
22     canvas.style = "border-radius: 15px";
23     canvas.style.border = "1px solid #3b3b3b";
24 };
25 initCanvas();
26 // 初始化画布
27 function initContext(cxt) {
28     cxt.lineCap="round";
29     cxt.lineJoin="round";
30     cxt.lineWidth = 1;
31 }
32 initContext(cxt);
33 // 开始画迷宫
34 function drawMaze(cxt) {
35     drawSingleBox(8, 0, 0, cxt);
36 };
37 /*setInterval(function(){
38     cxt.clearRect(0, 0, width, height);
39     drawMaze(cxt);
40 }, 50);*/
41 drawMaze(cxt);
42 // 递归画单元格
43 function drawSingleBox(option, posX, posY, cxt){
44     //cxt.strokeStyle = getColor();
45     switch(option){
46     case 0:
47         cxt.beginPath();
48         cxt.moveTo(posX, posY);
49         cxt.lineTo(posX + cellWidth, posY);
50         cxt.stroke();
51         break;
52     case 1:
53         cxt.beginPath();
54         cxt.moveTo(posX + cellWidth, posY);
55         cxt.lineTo(posX + cellWidth, posY + cellWidth);
56         cxt.stroke();
57         break;
58     case 2:
59         cxt.beginPath();
60         cxt.moveTo(posX, posY + cellWidth);
61         cxt.lineTo(posX + cellWidth, posY + cellWidth);
62         cxt.stroke();
63         break;
64     case 3:
65         cxt.beginPath();
66         cxt.moveTo(posX, posY);
67         cxt.lineTo(posX, posY + cellWidth);
68         cxt.stroke();
69         break;
70     }
71     if(posX >= width - cellWidth && posY >= height - cellWidth) {
72         return;
73     } else {
74         posX += cellWidth;
75         if(posX >= width){
76             posX = 0;
77             posY += cellWidth;
78         }
79         drawSingleBox(Math.floor(Math.random()*4), posX, posY, cxt);
80     }
81 }
82 // 随机出任意颜色
83 function getColor(){
84     var colorElements = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
85     var colorArray = colorElements.split(",");
86     var color ="#";
87     for(var i =0;i<6;i++){
88         color+=colorArray[Math.floor(Math.random()*16)];
89     }
90     return color;
91 }
92 </script>
93 </html>
生成随机迷宫
#去掉代码注释,神奇的一幕出现了,自己看看吧
1 setInterval(function(){
2     cxt.clearRect(0, 0, width, height);
3     drawMaze(cxt);
4 }, 50);
去掉此段代码的注释

猜你喜欢

转载自www.cnblogs.com/xhelper/p/9182275.html