Reputation: 640
I am trying to implement a canvas image that will contain a circle and a number of rectangles inside the circle. The circle will be generated according to the given diameter (user input) and the rectangles will be generated according to the given height and width (user inputs). The number of rectangles will be created according to the formula shown below.
Rectangles per Circle = d * pi * ((d / 4 * S) - (1 / sqrt(2 * S))) d – Circle Diameter S – Rectangle Size
For a 300px diameter circle, and 10px width with a 10px height rectangle, there will be 641 rectangles inside the circle.
But I need to place the rectangles properly inside the circle something like below.
Upvotes: 0
Views: 261
Reputation: 54089
You function d * pi * ((d / 4 * S) - (1 / sqrt(2 * S)))
does not work.
Below is an example that fits boxes SQUARE_SIZE
to a circle CIRCLE_RADIUS
via the function drawBoxesInCircle
and outputs to the console the number of boxes drawn.
const CIRCLE_RADIUS = 150;
const SQUARE_SIZE = 10;
// cx cy are circle center
// rad is circle radius
// size is box size
function drawBoxesInCircle(cx, cy, rad, size) {
var boxes = 0;
var y = 0;
for (y = 0; y < rad; y++) {
const boxCount = ((rad * rad - (y + size) ** 2) ** 0.5) / size | 0;
let i = 0;
while (i < boxCount) {
drawBox(cx + i * size, cy + y, size);
drawBox(cx - (1 + i) * size, cy + y, size);
drawBox(cx + i * size, cy - y - size, size);
drawBox(cx - (1 + i) * size, cy - y - size, size);
boxes += 4;
i++;
}
y += size;
}
console.log("Box count = " + boxes);
}
const TAU = Math.PI * 2;
const ctx = canvas.getContext("2d");
canvas.width = CIRCLE_RADIUS * 2 + 2;
canvas.height = CIRCLE_RADIUS * 2 + 2;
ctx.fillStyle = "#ffdcc8";
function strokeCircle(x, y, r) {
ctx.beginPath();
ctx.arc(x, y, r + 0.5, 0, TAU);
ctx.stroke();
}
function drawBox(x, y, size) {
ctx.beginPath();
ctx.rect(x, y, size, size);
ctx.fill();
ctx.stroke();
}
strokeCircle(CIRCLE_RADIUS + 1, CIRCLE_RADIUS + 1, CIRCLE_RADIUS);
drawBoxesInCircle(CIRCLE_RADIUS + 1, CIRCLE_RADIUS + 1, CIRCLE_RADIUS, SQUARE_SIZE);
canvas {
position: absolute;
top: 0px;
left: 0px;
}
<canvas id="canvas"></canvas>
Upvotes: 1