Implement surface painting
This commit is contained in:
parent
b4ae259123
commit
ccc48a3c8d
1 changed files with 39 additions and 6 deletions
45
js/Grid.js
45
js/Grid.js
|
@ -3,7 +3,7 @@ import {color, tool} from Toolbox;
|
|||
|
||||
var grid = {
|
||||
element: null,
|
||||
data: {}
|
||||
data: null
|
||||
};
|
||||
var down = false;
|
||||
|
||||
|
@ -17,13 +17,21 @@ function init(size, elementId) {
|
|||
grid.element.appendChild(
|
||||
makeRow({tag: 'td', attributes: bodyAttributes, row: row, size: size})
|
||||
);
|
||||
grid.data[row] = {};
|
||||
}
|
||||
grid.data = emptyGrid(size);
|
||||
grid.element.addEventListener('mouseleave', function() {
|
||||
down = false;
|
||||
});
|
||||
}
|
||||
|
||||
function emptyGrid(size) {
|
||||
var result = {};
|
||||
for(var i = 0; i < size; i++) {
|
||||
result[i] = {};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function makeRow(config) {
|
||||
var cells = [];
|
||||
for(var column = 0; column < config.size; column++) {
|
||||
|
@ -37,21 +45,46 @@ function bodyAttributes(i, j) {
|
|||
onMousedown: function(e) {
|
||||
down = true;
|
||||
if(tool() == 'draw') {
|
||||
colorize(i, j, e);
|
||||
colorize(i, j, e.target);
|
||||
}
|
||||
},
|
||||
onMouseup: function(e) {
|
||||
down = false;
|
||||
if(tool() == 'paint') {
|
||||
paint(i, j);
|
||||
}
|
||||
},
|
||||
onMouseenter: function(e) {
|
||||
if(down && tool() == 'draw') {
|
||||
colorize(i, j, e);
|
||||
colorize(i, j, e.target);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function colorize(i, j, e) {
|
||||
function colorize(i, j, element) {
|
||||
grid.data[i][j] = color();
|
||||
e.target.className = grid.data[i][j];
|
||||
element.className = grid.data[i][j];
|
||||
}
|
||||
|
||||
function paint(i0, j0) {
|
||||
var originColor = grid.data[i0][j0];
|
||||
var size = grid.element.children.length;
|
||||
var done = emptyGrid(size);
|
||||
var queue = [{i: i0, j: j0}];
|
||||
while(queue.length > 0) {
|
||||
var p0 = queue[0];
|
||||
colorize(p0.i, p0.j, grid.element.children[p0.i].children[p0.j]);
|
||||
done[p0.i][p0.j] = true;
|
||||
for(var d = -1; d < 2; d += 2) {
|
||||
[{i: p0.i + d, j: p0.j}, {i: p0.i, j: p0.j + d}].forEach(function(p1) {
|
||||
if(p1.i >= 0 && p1.i < size && p1.j >= 0 && p1.j < size
|
||||
&& !done[p1.i][p1.j]
|
||||
&& grid.data[p1.i][p1.j] == originColor) {
|
||||
queue.push(p1);
|
||||
}
|
||||
});
|
||||
}
|
||||
queue.shift();
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue