Implement surface painting

This commit is contained in:
Tissevert 2022-07-25 15:40:19 +02:00
parent b4ae259123
commit ccc48a3c8d

View file

@ -3,7 +3,7 @@ import {color, tool} from Toolbox;
var grid = { var grid = {
element: null, element: null,
data: {} data: null
}; };
var down = false; var down = false;
@ -17,13 +17,21 @@ function init(size, elementId) {
grid.element.appendChild( grid.element.appendChild(
makeRow({tag: 'td', attributes: bodyAttributes, row: row, size: size}) makeRow({tag: 'td', attributes: bodyAttributes, row: row, size: size})
); );
grid.data[row] = {};
} }
grid.data = emptyGrid(size);
grid.element.addEventListener('mouseleave', function() { grid.element.addEventListener('mouseleave', function() {
down = false; down = false;
}); });
} }
function emptyGrid(size) {
var result = {};
for(var i = 0; i < size; i++) {
result[i] = {};
}
return result;
}
function makeRow(config) { function makeRow(config) {
var cells = []; var cells = [];
for(var column = 0; column < config.size; column++) { for(var column = 0; column < config.size; column++) {
@ -37,21 +45,46 @@ function bodyAttributes(i, j) {
onMousedown: function(e) { onMousedown: function(e) {
down = true; down = true;
if(tool() == 'draw') { if(tool() == 'draw') {
colorize(i, j, e); colorize(i, j, e.target);
} }
}, },
onMouseup: function(e) { onMouseup: function(e) {
down = false; down = false;
if(tool() == 'paint') {
paint(i, j);
}
}, },
onMouseenter: function(e) { onMouseenter: function(e) {
if(down && tool() == 'draw') { 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(); 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();
}
} }