aboutsummaryrefslogtreecommitdiff
path: root/src/component/ImageBackground.astro
blob: 9277472fe7a39c49f8cf5b9b37c062050e612ff9 (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
---

---

<div class="bg">
  <slot/>
</div>

<script lang="js">
  document.querySelectorAll(".bg").forEach((e) => {
    const children = e.children;
    const max = e.clientWidth;
    const height = e.hasAttribute("data-height") ? e.getAttribute("data-height") : 400;
    const newChildren = [];

    let line = document.createElement("div");
    let currentWidth = 0;
    let i = 0;

    const fn = () => {
      let current = children[i++];
      let ratio = current.clientWidth / current.clientHeight;
      line.appendChild(current.cloneNode(true));
      currentWidth += ratio * height;
    }

    while (i < children.length) {
      // adding elements
      while (i < children.length && currentWidth <= max) fn()
      if (i < children.length) fn()
      // setting height
      let h = (max * height) / currentWidth;
      line.style.height = `${h}px`;
      newChildren.push(line);
      if (i < children.length) {
        line = document.createElement("div");
        currentWidth = 0
      }
    }
    e.replaceChildren(...newChildren);
  });
</script>