分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

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

发布时间:2023-09-06 01:59责任编辑:胡小海关键词:HTML
上效果图:
#先看生成随机迷宫的代码吧↓
 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);
去掉此段代码的注释

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

原文地址:https://www.cnblogs.com/xhelper/p/9182275.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved