我正试图让我的鼠标在一个大的正方形网格中将多个单元格变成黑色,因为我按住它并将鼠标移动到不同的单元格,但我的功能似乎只是让第一个单元格变黑然后停止。只要我按下鼠标按钮,它不应该继续下去吗?对不起,如果这是一个愚蠢的问题......非常感谢能给我一些见解的人。
document.addEventListener("mousedown", makeWall, false);
function makeWall(e) {
var mouseX = e.clientX - canvas.offsetLeft + window.scrollX;
var mouseY = e.clientY - canvas.offsetTop + window.scrollY;
if (mouseX >= 0 && mouseX <= canvas.width && mouseY >= 0 && mouseY <= canvas.height) {
var arrayC = Math.floor((mouseX - cellOffsetLeft)/ (cellWidth + cellPadding));
var arrayR = Math.floor((mouseY - cellOffsetTop)/ (cellHeight + cellPadding)); //all code above this just makes sure the x,y coordinates of where I'm clicking are correctly registered
changeCellColor(cells[arrayC][arrayR], black); //changes cell color to black for the first cell clicked on
}
}
答案 0 :(得分:0)
我找到了一些适合我需要的代码。感谢上面的nnnnnn让我朝着正确的方向前进。这是代码:
document.addEventListener("mousedown", makeWall, false);
document.addEventListener("mouseup", endWall, false);
function makeWall(e) {
document.addEventListener("mousemove", moveMouse, false);
}
function moveMouse (e) {
var mouseX = e.clientX - canvas.offsetLeft + window.scrollX;
var mouseY = e.clientY - canvas.offsetTop + window.scrollY;
if (mouseX >= 0 && mouseX <= canvas.width && mouseY >= 0 && mouseY <= canvas.height) {
var arrayC = Math.floor((mouseX - cellOffsetLeft)/ (cellWidth + cellPadding));
var arrayR = Math.floor((mouseY - cellOffsetTop)/ (cellHeight + cellPadding));
changeCellColor(cells[arrayC][arrayR], black);
}
}
function endWall(e) {
document.removeEventListener("mousemove", moveMouse, false);
}