Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: e5c9cd497bf36e2edc89371b217654e1702be972 (plain)
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
const svgns = "http://www.w3.org/2000/svg";
const dataset = document.currentScript.dataset;
const svg = document.querySelector('svg');
const gb = svg.querySelector('.gameboard');
const bg = svg.querySelector('#background');
const imageMaps = svg.querySelector('#image-maps');
const grid = gb.querySelector('.grid');

if ('cols' in dataset && 'rows' in dataset) {
  const cellTemplate = svg.querySelector('#hex');

  createCells(grid, dataset, cellTemplate.id);
}

const sequence = getComputedStyle(gb).transform.match(/-?\d+\.?\d*/g);
const mtx = new DOMMatrix(sequence || '');
bg.style.transform = mtx;

const bbox = grid.getBBox();

bbox.height += 5;

setElAttrs(bg, bbox);
svg.setAttribute('viewBox', formatForViewBox(calcComputedBboxFor(gb)));

function setElAttrs(el, attrs) {
  for (key in attrs) {
    el.setAttributeNS(null, key, attrs[key]);
  }
}

function formatForViewBox({ x, y, width, height }) {
  return `${x} ${y} ${width} ${height}`;
}

function calcComputedBboxFor(el) {
  const { x, y, width, height } = el.getBBox();
  const originPt = new DOMPoint(x, y);
  const maxPt = new DOMPoint(width + x, height + y);

  const sequence = getComputedStyle(el).transform.match(/-?\d+\.?\d*/g);
  const mtx = new DOMMatrix(sequence || '');

  const { x: originPtX, y: originPtY } = originPt.matrixTransform(mtx);
  const { x: maxPtX, y: maxPtY } = maxPt.matrixTransform(mtx);

  return { x: originPtX, y: originPtY, width: maxPtX - originPtX, height: maxPtY - originPtY };
}

function createCells(container, { cols, rows }, templateId) {
  for (let rowNum = 0; rowNum < +rows; rowNum++) {
    const row = document.createElementNS(svgns, 'g');
    row.dataset.y = rowNum;

    for (let colNum = 0; colNum < +cols; colNum++) {
      const cell = document.createElementNS(svgns, 'g');
      cell.dataset.x = colNum;

      const cellShape = document.createElementNS(svgns, 'use');
      cellShape.setAttribute('href', `#${templateId}`);

      cell.appendChild(cellShape);
      row.appendChild(cell);
    }

    container.appendChild(row);
  }
}