我用香草JS创建了一个像素网格,并添加了擦除和绘制模式。绘制模式的唯一点是在使用擦除模式后返回到默认功能(单击单元格或在多个单元格之间拖动时按下鼠标指针按钮时填充单元格)。
如果在选择“绘制”模式后尝试快速绘图,然后执行鼠标/释放鼠标指针,则整个网格将被填充,如果尝试单击“提交”以清除网格,它将无法工作。
我以前经历过网格填充问题,并用if语句修复了它。
if (e.target.tagName === 'TD') {
e.target.style.backgroundColor = color;
}它在默认函数控制绘图中工作(即,在选择擦除或绘制模式之前工作),并将其包含在用于绘制模式的函数中,但它并不能阻止填充网格,而且我不确定为什么单击'submit‘会在错误发生时清除网格。
要查看我的完整代码,请查看我的CodePen。
下面是我绘制模式的功能,它似乎是这些问题的根源:
// Allows user to return to (default) draw mode after using 'erase' button. Note 'down' was set to false in variable above
drawMode.addEventListener('click', function() {
pixelCanvas.addEventListener('mousedown', function(e) {
down = true;
pixelCanvas.addEventListener('mouseup', function() {
down = false;
});
// Ensures cells won't be colored if grid is left while pointer is held down
pixelCanvas.addEventListener('mouseleave', function() {
down = false;
});
pixelCanvas.addEventListener('mouseover', function(e) {
const color = document.querySelector('.color-picker').value;
// While mouse pointer is pressed and within grid boundaries, fills cell with selected color. Inner if statement fixes bug that fills in entire grid
if (down) {
if (e.target.tagName === 'TD') {
e.target.style.backgroundColor = color;
}
}
});
});
// Enables single-cell coloring while in draw mode
pixelCanvas.addEventListener('click', function(e) {
const color = document.querySelector('.color-picker').value;
e.target.style.backgroundColor = color;
});
});发布于 2018-03-30 06:57:01
如果在错误发生时检查HTML,您将看到表的背景色正在设置,这就是为什么不能擦除。尝试使用此方法,以确保将要着色的元素是像素(td),而不是其他任何元素:
pixelCanvas.addEventListener('click', function(e) {
if (e.target.tagName !== 'td') return;
const color = document.querySelector('.color-picker').value;
// ...https://stackoverflow.com/questions/49569811
复制相似问题