class Grid{ constructor(id, cell_size, mode = "STRETCH"){ this.id = id; this.$grid = $("#"+id); if (Array.isArray(cell_size)){ this.cell_width = cell_size[0]; this.cell_height = cell_size[1]; } else{ this.cell_width = cell_size; this.cell_height = cell_size; } this.columns = 0; this.rows = 0; const possible_mode = ["STRETCH", "FIXED", "SPACE"]; if(possible_mode.includes(mode)){ this.mode = mode; } // this.init_css(); this.elements = []; this.distribute = function(i,j){ // default distribution if there is more than one element let index = j; let choose = (index+(i%this.elements.length))%this.elements.length; return choose; } this.mouvements = []; } init_css(){ // get the new element because pagedjs changed it this.$grid = $("#"+this.id); // compute number of cell that can fit horizontaly and verticaly this.columns = String(Math.floor(this.$grid.width() / this.cell_width)); this.rows = String(Math.floor(this.$grid.height() / this.cell_height)); console.log(this.$grid.width(), this.$grid.height()); console.log("col-row-size", this.columns, this.rows, "(" + this.cell_width + "px", this.cell_width + "px" + ")"); // init css grid this.$grid.css("display", "grid"); if(this.mode == "STRETCH" || this.mode == "SPACE"){ this.$grid.css("grid-template-columns", "repeat("+ this.columns +", 1fr"); this.$grid.css("grid-template-rows", "repeat("+ this.rows +", 1fr"); } else{ this.$grid.css("grid-template-columns", "repeat("+ this.columns +", "+ this.cell_width + "px"); this.$grid.css("grid-template-rows", "repeat("+ this.rows +", "+ this.cell_height + "px"); } } addElement(element_template){ this.elements.push(element_template); } addMouvement(grid_mouvement){ this.mouvements.push(grid_mouvement); } draw(){ // fill all the grid with it's element this.init_css(); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { // pick the element we are going to draw let pick = this.distribute(i,j); let element_html = ""; if(pick >= 0){ element_html = this.elements[pick].html; } // a clone let $el = $(element_html); // wrapp it in a cell let $cell = $("