1

Trying to build the Game of Life here with React JS. I have a 2-dimensional array that holds the state of the grid. Every element, which is an array, represents a row and a sub-element is either 0 or 1 (dead or alive).

I want to use HTML Canvas to draw the grid based on this array and also add a click function that returns the matching element in the array so I can write a function to change it to 0 or 1 based on an algorithm.

I have a general idea how to draw a grid, also checked this link

But i am not sure whether this is the way to do it so I can identify each cell with a click. And also stuck on how I can return the cell to match the array element. Anyone can help me with this?

I am also aware of this question on Stack Overflow, but the answers are implementations with HTML or SVG, I am looking for a canvas implementation.

Community
  • 1
  • 1
chemook78
  • 1,168
  • 3
  • 17
  • 38

1 Answers1

2

First of all you have to handle the click event. Here you can find a good description of how: How do I add a simple onClick event handler to a canvas element?.

Furthermore, you just use the x and y of the clicked point to determine what tile has been clicked. Lets say you have 10 x 10 tiles with the height and width of 10 px.

If the user clicks the coordnate 67,12 you can divide x and y by ten, and round it off to know which elelemt in your 2d array that represents it.

Community
  • 1
  • 1
LeFex
  • 258
  • 1
  • 10