-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathRecursiveImages.js
91 lines (72 loc) · 2.82 KB
/
RecursiveImages.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class RecursiveImages extends HTMLElement {
constructor() {
super();
this.shadow = this.attachShadow({ mode: 'open' });
this.shadow.innerHTML = `<style>
:host {display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; }
canvas { max-width: 100%; max-height: 100%; }
</style>`;
this.canvas = document.createElement('canvas');
this.shadow.appendChild(this.canvas);
this.ctx = this.canvas.getContext('2d');
this._inscriptions = [];
this._gridArrays = [];
this._gridRows;
this._gridColumns;
this._width;
this._height;
}
connectedCallback() {
this._inscriptions = JSON.parse(this.getAttribute('inscriptions'));
this._gridRows = parseInt(this.getAttribute('grid').split('x')[0]);
this._gridColumns = parseInt(this.getAttribute('grid').split('x')[1]);
this._width = parseInt(this.getAttribute('width'));
this._height = parseInt(this.getAttribute('height'));
this.canvas.width = this._width;
this.canvas.height = this._height;
this._gridArrays = this.generateGridArray(this._inscriptions.length, this._gridRows, this._gridColumns);
this.render();
}
async render() {
const imgWidth = this._width;
const imgHeight = this._height;
const sliceWidth = Math.round(imgWidth / this._gridRows);
const sliceHeight = Math.round(imgHeight / this._gridColumns);
const widthLastColumn = imgWidth - sliceWidth * (this._gridRows - 1);
const heightLastRow = imgHeight - sliceHeight * (this._gridColumns - 1);
const imagePromises = this._inscriptions.map((inscription) => this.createImageFromBase64(inscription));
const images = await Promise.all(imagePromises);
for (let g = 0; g < this._gridArrays.length; g++) {
for (let c = 0; c < this._gridArrays[g].length; c++) {
const img = images[this._gridArrays[g][c]];
const x = c * sliceWidth;
const y = g * sliceHeight;
const w = c === this._gridRows - 1 ? widthLastColumn : sliceWidth;
const h = g === this._gridColumns - 1 ? heightLastRow : sliceHeight;
this.ctx.drawImage(img, x, y, w, h);
}
}
}
async createImageFromBase64(base64) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = base64;
});
}
generateGridArray(length, gridRows, gridColumns) {
const multiDimensionalArray = [];
let element = 0;
for (let row = 0; row < gridRows; row++) {
const currentRow = [];
for (let col = 0; col < gridColumns; col++) {
currentRow.push(element);
element = (element + 1) % length;
}
multiDimensionalArray.push(currentRow);
}
return multiDimensionalArray;
}
}
customElements.define('recursive-images', RecursiveImages);