How to paint multiple page elements by clicking and dragging the mouse?

4

Essentially my program creates a "screen" of "pixels" where the divs are the pixels.

It randomly generates the colors in the image and the user can use a palette that is underneath to change, as if it were to paint.

However, I have a dilemma: I would like the user to click with the mouse and drag to paint, instead of clicking div to div . I tried some listeners , but it did not work.

Follow the codes! Thanks in advance!

var updateTela = false;
var corSelecionada = "white";

window.onload = function() {
  geraPegaCor();

}

function iniciaGerador() {


  if (updateTela == false) { //Se a tela ainda não foi gerada
    updateTela = true;
    geraTela();
  } else if (updateTela == true) { //Se a tela já foi gerada

    geraImagem(1290);
  } else { //MSG de Erro
    alert("error");
  }
}

function geraTela() { //Gera a tela (os pixels e o palco de pixels)

  var palco = document.getElementById('palcopixel'); //holder do palco de          pixels
  palco.style.height = "363px";
  //começa a montar os pixels, div a div

  //laço de numerode linhas
  var nLinhas = 0;
  var nPixel = 0;
  while (nLinhas < 30) {
    var n = 1;
    while (n < 44) {
      nPixel++;

      var divPixel;
      divPixel = document.createElement("div");
      divPixel.setAttribute("id", "pixel" + nPixel)
      divPixel.setAttribute("class", "pixel");
      palco.appendChild(divPixel);
      n++;
    }

    nLinhas++;
  }

  geraImagem(nPixel);
}

function geraImagem(numeroPixel) {
  var contaDiv = 1;

  while (contaDiv <= numeroPixel) {
    var corRandom;
    var tabelaCores = ['blue', 'yellow', 'red', 'green', 'pink', 'cyan', 'black', 'brown', 'tomato', 'violet'];
    var pixelClassHolder;

    corRandom = Math.floor(Math.random() * 10);

    pixelClassHolder = document.getElementById("pixel" + contaDiv);

    corSelecionada = tabelaCores[corRandom];
    //console.log(corSelecionada);
    pixelClassHolder.style.background = tabelaCores[corRandom]
    pixelClassHolder.setAttribute("onclick", "pintaTela('pixel" + contaDiv + "')");
    contaDiv++;


  }

  var corSelecionada = "white";

}

function geraPegaCor() {

  var paletaPegaCor = document.getElementById('pegaCor');
  var contaPegaCor = 0;
  var tabelaCores = ['blue', 'yellow', 'red', 'green', 'pink', 'cyan', 'black', 'brown', 'tomato', 'violet'];

  while (contaPegaCor < tabelaCores.length) {

    var divColorPicker;
    divColorPicker = document.createElement("div");
    divColorPicker.setAttribute("id", "corPegavel" + contaPegaCor)
    divColorPicker.setAttribute("class", "corPegavel");
    paletaPegaCor.appendChild(divColorPicker);
    divColorPicker.style.background = tabelaCores[contaPegaCor];
    divColorPicker.setAttribute("onclick", "cataCor('" + tabelaCores[contaPegaCor] + "')")


    contaPegaCor++;
  }
}

/******************************/
/*   FERRAMENTAS DE PINTURA   */
/******************************/
function cataCor(corCatada) { //PEGA COR DOS CONTROLES

  $("#corselecionada").css("color", corCatada);
  $("#corselecionada").text(corCatada);
  corSelecionada = corCatada;
  document.body.style.cursor = "crosshair";

}

function limpaCor() {
  $("#corselecionada").css("color", "black");
  $("#corselecionada").text("Branco");
  document.corSelecionada = "white";
}

function pintaTela(divSelecionada) {


  $("#" + divSelecionada + "").css("background", "" + corSelecionada + "");

  console.log(corSelecionada);


}







/*****************************/
/*         ESTETICA         */
/***************************/
//HOVER DAS CORES
$(".corPegavel").hover(function() {
  $(this).animate({
    opacity: 0.25
  }, 200);

});

$(".corPegavel").mouseleave(function() {
  $(this).animate({
    opacity: 1
  }, 100);
});
//
body {}

#palcopixel {
  width: 483px;
}

.pixel {
  width: 10px;
  height: 10px;
  background-color: blue;
  float: left;
  margin-right: 1px;
  margin-bottom: 1px;
}

#controles {}

#pegaCor {
  margin-top: 5px;
  /*float: left;
    position: relative;*/
}

.corPegavel {
  margin-right: 1px;
  float: left;
  width: 15px;
  height: 15px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="palcopixel"></div>
<div id="controles">
  <input type="button" name="geraimagembotao" onclick="iniciaGerador()" value="Gere a imagem">
  <input type="button" name="limpadordecor" onclick="limpaCor()" value="Limpar Pincel">
  <div>Cor Selecionada: <span id="corselecionada">Branco</span></div>
  <div id="pegaCor">

  </div>
</div>
    
asked by anonymous 26.10.2018 / 21:03

1 answer

4

In a very trivial way, without analyzing all your code, you can create a clicado variable, of type Boolean, which will be true while the mouse is pressed. In event% with% of its elements you set it to true and in event mousedown it to false. In the mouseup event, which is when the mouse is over the element, you check whether the variable is true and, if so, change the background color.

I basically did this by adding the code:

divPixel.addEventListener('mousedown', function () {
  clicado = true;
});

divPixel.addEventListener('mouseup', function () {
  clicado = false;
});

divPixel.addEventListener('mouseover', function () {
  if (clicado) {
    this.style.backgroundColor = corSelecionada;
  }
});

See how it went:

var updateTela = false;
var corSelecionada = "white";
var clicado = false;

window.onload = function() {
  geraPegaCor();

}

function iniciaGerador() {


  if (updateTela == false) { //Se a tela ainda não foi gerada
    updateTela = true;
    geraTela();
  } else if (updateTela == true) { //Se a tela já foi gerada

    geraImagem(1290);
  } else { //MSG de Erro
    alert("error");
  }
}

function geraTela() { //Gera a tela (os pixels e o palco de pixels)

  var palco = document.getElementById('palcopixel'); //holder do palco de          pixels
  palco.style.height = "363px";
  //começa a montar os pixels, div a div

  //laço de numerode linhas
  var nLinhas = 0;
  var nPixel = 0;
  while (nLinhas < 30) {
    var n = 1;
    while (n < 44) {
      nPixel++;

      var divPixel;
      divPixel = document.createElement("div");
      divPixel.setAttribute("id", "pixel" + nPixel)
      divPixel.setAttribute("class", "pixel");
      
      divPixel.addEventListener('mousedown', function () {
        clicado = true;
      });
      
      divPixel.addEventListener('mouseup', function () {
        clicado = false;
      });
      
      divPixel.addEventListener('mouseover', function () {
        if (clicado) {
          this.style.backgroundColor = corSelecionada;
        }
      });
      
      palco.appendChild(divPixel);
      n++;
    }

    nLinhas++;
  }

  geraImagem(nPixel);
}

function geraImagem(numeroPixel) {
  var contaDiv = 1;

  while (contaDiv <= numeroPixel) {
    var corRandom;
    var tabelaCores = ['blue', 'yellow', 'red', 'green', 'pink', 'cyan', 'black', 'brown', 'tomato', 'violet'];
    var pixelClassHolder;

    corRandom = Math.floor(Math.random() * 10);

    pixelClassHolder = document.getElementById("pixel" + contaDiv);

    corSelecionada = tabelaCores[corRandom];
    //console.log(corSelecionada);
    pixelClassHolder.style.background = tabelaCores[corRandom]
    pixelClassHolder.setAttribute("onclick", "pintaTela('pixel" + contaDiv + "')");
    contaDiv++;


  }

  var corSelecionada = "white";

}

function geraPegaCor() {

  var paletaPegaCor = document.getElementById('pegaCor');
  var contaPegaCor = 0;
  var tabelaCores = ['blue', 'yellow', 'red', 'green', 'pink', 'cyan', 'black', 'brown', 'tomato', 'violet'];

  while (contaPegaCor < tabelaCores.length) {

    var divColorPicker;
    divColorPicker = document.createElement("div");
    divColorPicker.setAttribute("id", "corPegavel" + contaPegaCor)
    divColorPicker.setAttribute("class", "corPegavel");
    paletaPegaCor.appendChild(divColorPicker);
    divColorPicker.style.background = tabelaCores[contaPegaCor];
    divColorPicker.setAttribute("onclick", "cataCor('" + tabelaCores[contaPegaCor] + "')")


    contaPegaCor++;
  }
}

/******************************/
/*   FERRAMENTAS DE PINTURA   */
/******************************/
function cataCor(corCatada) { //PEGA COR DOS CONTROLES

  $("#corselecionada").css("color", corCatada);
  $("#corselecionada").text(corCatada);
  corSelecionada = corCatada;
  document.body.style.cursor = "crosshair";

}

function limpaCor() {
  $("#corselecionada").css("color", "black");
  $("#corselecionada").text("Branco");
  document.corSelecionada = "white";
}

function pintaTela(divSelecionada) {


  $("#" + divSelecionada + "").css("background", "" + corSelecionada + "");

  console.log(corSelecionada);


}







/*****************************/
/*         ESTETICA         */
/***************************/
//HOVER DAS CORES
$(".corPegavel").hover(function() {
  $(this).animate({
    opacity: 0.25
  }, 200);

});

$(".corPegavel").mouseleave(function() {
  $(this).animate({
    opacity: 1
  }, 100);
});
//
body {}

#palcopixel {
  width: 483px;
}

.pixel {
  width: 10px;
  height: 10px;
  background-color: blue;
  float: left;
  margin-right: 1px;
  margin-bottom: 1px;
}

#controles {}

#pegaCor {
  margin-top: 5px;
  /*float: left;
    position: relative;*/
}

.corPegavel {
  margin-right: 1px;
  float: left;
  width: 15px;
  height: 15px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="palcopixel"></div>
<div id="controles">
  <input type="button" name="geraimagembotao" onclick="iniciaGerador()" value="Gere a imagem">
  <input type="button" name="limpadordecor" onclick="limpaCor()" value="Limpar Pincel">
  <div>Cor Selecionada: <span id="corselecionada">Branco</span></div>
  <div id="pegaCor">

  </div>
</div>

The fact is that if you click on the image, drag it out and release the mouse, it will paint continuously even without pressing the mouse, because the mouseover event does not occur in the element and, therefore, the variable does not back to false. You can change this as needed by capturing the appropriate events in JavaScript.

    
26.10.2018 / 21:22