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/