0

I have a basic canvas square with a grid of rectangles inside, how can I create click events that change the fill color of a specific rectangle within the grid when clicked. Is there a method to fit inside of the loop coordinate detection or is there a better library that will create clickable rectangles?

Here is a demo of my work: https://codesandbox.io/s/brave-worker-ywe3z5

const App = () => {
  const canvasRef = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const context = canvas.getContext("2d");

    context.imageSmoothingEnabled = false;
    context.fillStyle = "#000000";
    context.fillRect(0, 0, context.canvas.width, context.canvas.height);

    for (var y = 1; y <= 1000; y += 11) {
      for (var x = 1; x <= 1000; x += 11) {
        context.fillStyle = "rgba(255,255,255,0.1)";
        context.lineWidth = 1;
        context.fillRect(x, y, 10, 10);
      }
    }
  }, []);

  return <canvas ref={canvasRef} width={1002} height={1002}></canvas>;
};

ReactDOM.render(<App/>, document.getElementById('root'));
.App {
  font-family: sans-serif;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Here is a sample of something I'm trying to achieve: https://www.sandbox.game/en/map/

Mushroomator
  • 6,516
  • 1
  • 10
  • 27
Shimsho
  • 107
  • 9
  • 1
    Either do the maths yourself using the `onClick` event of `` or and that's what I recommend use a library that does all this for you. You could use [`react-konva`](https://konvajs.org/docs/react/index.html) for example. – Mushroomator Apr 21 '22 at 13:43
  • If I understand it correctly, canvas ref is referencing an html element. I think you can bind events with ref.current.addEventListener – Mücahit Inel Apr 21 '22 at 13:45

0 Answers0