Create a circular or triangular shaped board

Viewed 30

I'm trying to create a game board ( similar to a chess board) for a game in react, and I would like to arrenge the cells (rectangular divs, that take they're value from a state array) in different shapes ( circle, triangle, oval etc) thus creating a board of that shape. I only know how to arrange divs with CSS flex or grid and that is always rectangular formation (as far as I know)

How can I achieve this?

Any help will be appreciated, thanks!

1 Answers

To dynamically position elements, you need to arrange them in code. We can do that by creating the elements in code, then setting their position programmatically. I'm working off this jsfiddle

First, the HTML:

<div id="my_container" />

It couldn't get simpler. We just want somewhere we can put our elements. Now, for minimal styling, we've got:

#my_container {
  position: relative;
  width: 200px;
  height: 200px;
  background-color: powderblue
}

.cell {
  background-color: red;
  width: 5px;
  height: 5px;
  position: absolute;
}

I've added colors so that you can see the elements in the generated output, but they're not necessary. What is necessary is those position lines. Making the #container div relative lets it behave nicely with whatever it's placed in, and making each of the .cell divs absolute causes them to be placed on absolute coordinates relative to their parent, which means we can put them where we want. Ok, what's next?

The cells. I assume your cells already exist, but since I don't have them, I've created code to build these cells, shown below:

const container = document.getElementById("my_container");
const number_of_cells = 30;
const cells = [];
for (var i = 0; i < number_of_cells; i++)
{
    const newDiv = document.createElement("div");
    newDiv.classList.add("cell");
    container.appendChild(newDiv)
    cells.push(newDiv); 
}

The goal here is to put the cells as children of #my_container and also create an array of all the cells. (I think maybe this step is redundant but I don't care...It makes the next step easier.)

function PositionCells(cells, x, y, radius)
{
  const incr_angle = (2*Math.PI)/cells.length;
  for (let i = 0; i < cells.length; i++) {
      var new_x = x+radius * Math.cos(incr_angle * i);
      var new_y = y+radius * Math.sin(incr_angle * i);
      cells[i].style.left = new_x+'px';
      cells[i].style.top = new_y+'px';
  }
}
PositionCells(cells, 50,50,30);

Basically what I've done is written a function to position all the cells in an ordered, programmatic way. If you want other shapes, you can pretty easily do the math to come up with where to position them.

And that's it!

Related