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

Asked

Viewed 107 times

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 below to change, as if to paint.

However, I have a dilemma: I wish the user could click with the mouse and drag to paint, rather than click div to div. I tried some listeners, but it didn’t work.

Follow the codes! From now on, thank you!

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>

<div id="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>

  • 3

    I improved your question by removing unnecessary text and creating the snippet so that the code is reproducible on the website. You can do the [tour], read the [Ask] guide and go to [help] to learn more about how the website works. If in doubt, you can ask on [meta]. Welcome.

1 answer

4


In a very trivial way, without analyzing all your code, you can create a variable clicado, boolean type, which will be true while the mouse is pressed. In the event mousedown of its elements you define it as true and in the event mouseup as false. In the event mouseover, which is when the mouse is over the element, you check whether the variable is true and, if yes, changes the background color.

I did it basically 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;
  }
});

Look how it turned out:

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>

<div id="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>

Fact is that so if you click on the image, drag it out and drop the mouse, will be painting continuously even without pressing the mouse, because the event mouseup does not occur in the element and therefore the variable does not return to false. You can change this as needed by capturing the right events in Javascript.

  • Damn, man, amazing how JS has such quiet exits. It worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.