Published
Edited
Jul 15, 2020
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
ncircles
Insert cell
Insert cell
{
let ctx = canvas.getContext("2d");
let square = Math.sqrt(canvas.width*canvas.height/ncircles)
let times_height = canvas.height/square
let times_width = canvas.width/square
let round_times_height = Math.round(times_height)
let round_times_width = Math.round(times_width)
if(round_times_height*round_times_width < ncircles){
let heightDiff = round_times_height - times_height
let widthDiff = round_times_width - times_width
if(heightDiff < 0 && heightDiff < widthDiff){
console.log('soma altura')
round_times_height++
} else if (widthDiff < 0 && widthDiff < heightDiff){
console.log('soma largura')
round_times_width++
}
}

// This line is not quite right...
let sideWidth = canvas.width/round_times_width
let sideHeight = canvas.height/round_times_height
let squareSide = 0
if(sideWidth < sideHeight){
squareSide = sideWidth
}else {
squareSide = sideHeight
}

// My solution is identical to the code below...
let perRow = Math.floor(canvas.width / squareSide)
let circleRadius = squareSide / 4;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = "black";
ctx.strokeStyle = "gray";
for (let i = 0; i < ncircles; i++) {
let row = Math.floor(i/perRow);
let col = i % perRow;
let x = circleRadius * 2 + circleRadius*4*col;
let y = circleRadius * 2 + circleRadius*4*row;
ctx.beginPath ();
ctx.arc (x,y,circleRadius,0,Math.PI*2)
ctx.fill()
ctx.beginPath ();
ctx.moveTo(x-squareSide/2,y-squareSide/2);
ctx.lineTo(x-squareSide/2,y+squareSide/2);
ctx.lineTo(x+squareSide/2,y+squareSide/2);
ctx.lineTo(x+squareSide/2,y-squareSide/2);
ctx.closePath();
ctx.stroke()
}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more