Constellations/js/Grid.js

58 lines
1.1 KiB
JavaScript
Raw Normal View History

2022-07-23 18:33:01 +02:00
import * as Dom from UnitJS.Dom;
import {color, tool} from Toolbox;
2022-07-23 18:33:01 +02:00
2022-07-24 11:20:22 +02:00
var grid = {
element: null,
data: {}
};
var down = false;
2022-07-23 18:33:01 +02:00
return {
init: init
2022-07-24 11:20:22 +02:00
};
2022-07-23 18:33:01 +02:00
2022-07-24 11:20:22 +02:00
function init(size, elementId) {
grid.element = document.getElementById(elementId || 'grid');
2022-07-23 18:33:01 +02:00
for(var row = 0; row < size; row++) {
2022-07-24 11:20:22 +02:00
grid.element.appendChild(
makeRow({tag: 'td', attributes: bodyAttributes, row: row, size: size})
);
grid.data[row] = {};
2022-07-23 18:33:01 +02:00
}
grid.element.addEventListener('mouseleave', function() {
down = false;
});
}
function makeRow(config) {
var cells = [];
2022-07-24 11:20:22 +02:00
for(var column = 0; column < config.size; column++) {
cells.push(Dom.make(config.tag, config.attributes(config.row, column)));
}
return Dom.make('tr', {}, cells);
}
2022-07-24 11:20:22 +02:00
function bodyAttributes(i, j) {
return {
onMousedown: function(e) {
down = true;
if(tool() == 'draw') {
colorize(i, j, e);
}
},
onMouseup: function(e) {
down = false;
},
onMouseenter: function(e) {
if(down && tool() == 'draw') {
colorize(i, j, e);
}
}
};
2022-07-23 18:33:01 +02:00
}
function colorize(i, j, e) {
grid.data[i][j] = color();
e.target.className = grid.data[i][j];
}