グリッド内に一連のほぼ正方形のポリゴンを生成するインタラクティブなデジタル キャンバスを作成したいと考えています。以下の 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;
}