I am writing a simple piece of code to draw pixels wherever the mouse is. I also want to have a clear button. Drawing works fine, but I can't get the button to work. Here are the relevant parts of my .js file:
function pixel(x, y) {
var pix = document.createElement("div");
pix.setAttribute("style", "position:absolute;left:" + x + "px;top:" +
y + "px;width:3px;height:3px;background:#000;cursor:crosshair");
return pix;
}
var mouseDown = false;
function draw(event) {
if (!mouseDown) return;
var x = event.clientX;
var y = event.clientY;
document.getElementById("box").appendChild(pixel(x, y));
}
function clear() {
var box = document.getElementById("box");
for (n in box.childNodes)
box.removeChild(n);
}
Relevant part of my HTML file:
<body onmousedown="mouseDown=true" onmouseup="mouseDown=false">
<div id="box" onmouseover="document.getElementById('box').style.cursor='crosshair'"
onmousemove="draw(event)"></div>
<button onclick="clear()">Clear</button>
</body>
The box is also formatted a bit using CSS, but that shouldn't be a problem. I feel that the problem may be that I am removing pixels from the window, but not from the document or something else, but I have JavaScript noob, so I donβt know.
Nick source
share