Search code examples
javascriptclickaddeventlisteneronmouseoveronmousedown

Need help creating a drawing tool for pixel drawing using mouse drag and release in Javascript


Oh hey! I am a JavaScript beginner playing around with DOM and I am currently facing an issue for which I have been unable to find a solution. What I've wanted is to paint each sqaure divs acting as pixels/cells and anytime you clicked and/or dragged the mouse, it'll change each div's background color as if it's like standard painting application. In the first code block below is what I ended up using but it isn't what I wanted, it can only paint each individual pixels/cells by clicking one on one. I attempted using EventListener with onmousedown or mouseover nested inside an EventListener with Click. However, this was unsuccessful. I had hoped that after clicking, the next EventListener would be detected and I would be able to draw like many other standard drawing apps. Would appreciate if anyone point me in the right direction.

 document.querySelectorAll(".PixelBoxes").forEach(element => {
    element.addEventListener("click", () => {
        console.log(colorPicker.color.hexString);
        element.style.backgroundColor = colorPicker.color.hexString;
    })
  });

This is the messy unsuccessful code I tried to describe earlier.

element.addEventListener("click", () => {
    console.log(colorPicker.color.hexString);
    element.style.backgroundColor = colorPicker.color.hexString;

    document.querySelectorAll(".PixelBoxes").forEach( element => {
        element.addEventListener("mouseover", () => {
          element.style.backgroundColor = colorPicker.color.hexString;
        })
    })
}

Here's my codepen to see everything in works and the part I'm working at related to this post is on line 126 of JS section (CSS responsive design may be little wonky): https://codepen.io/DawnofSouls/pen/GRXeQRo

As stated before, what I've wanted is to create a some sort of drawing feature like many standard drawing applications have. At first, I've tried putting a onmousedown or mouseover inside of eventlisten click to achieve the standard brush/pencil tool that ended up not working the way I wanted. It instead painted each pixels nonstop even after letting go off the mouse.

Thank you! :D


Solution

  • No judgment here only tips to help you ;)

    At start you need to do pseudo code , and realize wich function you need to avoid spagetti code while you begin to type and debug . Creating a "the_thing_i_want_to_do" library if you like .

    You need to detect when clic is released and apply color only if clic is on like :

        var mouseDown = 0;
        document.body.onmousedown = function() { 
          ++mouseDown;
        }
        document.body.onmouseup = function() {
          --mouseDown;
        }
    

    So inside: element.addEventListener("mouseover", () => {

    you can use it like this :

        if(mouseDown){
      // change color of destination 
        }