我想创建一个交互式数字画布,它将在网格中生成一系列接近正方形的多边形。下面的 jsFiddle 显示了所述多边形的 2x2 网格系统。如果您检查代码或刷新页面,您会看到中心顶点是 4 个相邻多边形共享的半随机生成点。
我想将此网格缩放到 16x16 附近,每个内部顶点都是半随机生成的,但在当前状态下,完成的代码效率低下、不灵活且不可扩展。我知道那里有一个相对简单的解决方案,但考虑到我对 for 循环和数组的经验不足,它目前超出了我的范围。任何帮助是极大的赞赏。
HTML:
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
</body>
JS:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var randomX = Math.floor((Math.random()-0.5)*30);
var randomY = Math.floor((Math.random()-0.5)*30);
var x1 = canvas.width/2 + randomX;
var x2 = canvas.width;
var y1 = canvas.height/2 + randomY;
var y2 = canvas.height;
//background
context.beginPath();
context.rect(0,0,canvas.height,canvas.width);
context.fillStyle = '#A3DCEE';
context.fill();
//top left polygon
context.beginPath();
context.lineTo(0,0); //top left quadrant
context.lineTo(canvas.width/2,0); //top right quadrant
context.lineTo(x1, y1); //bottom right quadrant
context.lineTo(0, canvas.width/2); //bottom left quadrant
context.closePath();
context.fillStyle = '#ABE2EF';
context.fill();
//top right polygon
context.beginPath();
context.lineTo(x2/2,0); //top left quadrant
context.lineTo(x2,0); //top right quadrant
context.lineTo(x2, y2/2); //bottom right quadrant
context.lineTo(x1, y1); //bottom left quadrant
context.closePath();
context.fillStyle = '#A3DCEE';
context.fill();
//bottom left polygon
context.beginPath();
context.lineTo(0,y2/2); //top left quadrant
context.lineTo(x1,y1); //top right quadrant
context.lineTo(x2/2, y2); //bottom right quadrant
context.lineTo(0, y2); //bottom left quadrant
context.closePath();
context.fillStyle = '#8CD6F6';
context.fill();
//bottom right polygon
context.beginPath();
context.lineTo(x1,y1); //top left quadrant
context.lineTo(x2,y2/2); //top right quadrant
context.lineTo(x2, y2); //bottom right quadrant
context.lineTo(x2/2, y2); //bottom left quadrant
context.closePath();
context.fillStyle = '#85D2ED';
context.fill();
CSS:
html, body {
background-color: #fff;
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
position: relative;
}
canvas {
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}