Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
How to color the background of a canvas coordinate grid on click using javascript?

How to select multiple squares and on click change their background color on a canvas with javascript?

So far I am able to "draw" the canvas and the coordinate grid. The part I am not able to figure out is how to change the background color of a selected square and how to do the same thing with multiple squares (selecting them with the mouse)?

function draw() {

      var canvas = document.getElementById('canvas');
      if (canvas.getContext) {
        var context = canvas.getContext('2d');

        for(var x=0.5;x<500;x+=10) {
          context.moveTo(x,0);
          context.lineTo(x,500);
        }

        for(var y=0.5; y<500; y+=10) {
          context.moveTo(0,y);
          context.lineTo(500,y);

      }

      context.strokeStyle='grey';
      context.stroke();

  }
}

function color(event) {
    var x = event.clientX - 10;
    var y = event.clientY - 10;
    
    console.log(x + ' ' + y);
    // how to color the selected squares?
  }
#canvas { border: 1px solid black;}
<body onload='draw()'>
    <div id=container>
      <canvas id='canvas' width='500' height='500' onclick="color(event)"></canvas>
    </div>
</body>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It is a good idea to maintain a state. Here I start off creating an two dimensional array (an array of arrays) that holds an object. The state of the object can be selected=true|false.

In the draw() function I iterate the array and set the fillStyle according to the state of the object.

In the color() function I calculate the index of an object and set the selected property to true. And then I draw the canvas again.

var squares = [...new Array(50)].map((a,i) => [...new Array(50)].map((a,i) => {return {selected: false};}));

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
function draw() {
  if (canvas.getContext) {
    context.fillStyle = 'black';
    context.fillRect(0, 0, 501, 501);
    squares.forEach((line, i) => {
      line.forEach((square, j) => {
        context.fillStyle = (square.selected) ? 'red' : 'white';
        context.fillRect(10*j+1, 10*i+1, 9, 9);
      });
    });
  }
}

function color(event) {
  var x = Math.floor((event.clientX - 10) / 10);
  var y = Math.floor((event.clientY - 10) / 10);
  squares[y][x].selected = true;
  draw();
}
#canvas {
  /*border: 1px solid black;*/
}
<body onload='draw()'>
  <div id=container>
    <canvas id='canvas' width='501' height='501' onclick="color(event)"></canvas>
  </div>
</body>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda