本篇教程介绍了JavaScript生成随机迷宫详解,希望阅读本篇文章以后大家有所收获,帮助大家对JavaScript的理解更加深入。
<
#先看生成随机迷宫的代码吧↓
1
2
3
生成随机迷宫v1.04
5
6
7
8
生成随机迷宫v1.0
9 刷新
10
11
12
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
93
生成随机迷宫
#去掉代码注释,神奇的一幕出现了,自己看看吧
1 setInterval(function(){
2 cxt.clearRect(0, 0, width, height);
3 drawMaze(cxt);
4 }, 50);
去掉此段代码的注释
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标WEB前端JavaScript频道!