I am trying to create a pixel painting project using HTML, CSS, and JS. I am having trouble with the painting mechanics.
expected result:
mousedown –> being able to move mouse and paint using mouseover –> mouseup (stop painting)
I originally did this:
for (let i = 0; i <= pixels.length; i++) {
pixels[i]?.addEventListener("mouseover", () => {
pixels[i].setAttribute("style", "background: black");
console.log("painting");
})
}
and this works when the mouse is over the canvas. but this doesn’t include the mousedown/mouseup mechanic. so, I tried this:
try 1:
if (mouseDown) {
pixels.forEach(pixel => {
pixel.style.background = colorSelector.value;
pixel.addEventListener("mouseover", function coloring(event) {
pixel.style.background = colorSelector.value;
if (!mouseDown) {
pixel.removeEventListener("mouseover", coloring);
}
})
})
}
try 2:
pixels.forEach(pixel => {
if (mouseDown) {
//to color the first pixel clicked
pixel.style.background = colorSelector.value;
pixel.addEventListener("mouseover", function coloring(event) {
pixel.style.background = colorSelector.value;
if (!mouseDown) {
//remove the coloring if the mouse button is up
pixel.removeEventListener("mouseover", coloring);
}
})
}
})
But none seem to work. I have checked the mouseDown and it works so I am not sure why it doesn’t execute.