通过JS生成蜂巢背景图(六边形背景图)

先看效果
在这里插入图片描述
再看思路
1、通过document.querySelector获取这个SVG对象
2、使用document.createElementNS创建一个带http://www.w3.org/2000/svg命名空间的矩形对象
3、使用element.setAttribute设置这个矩形对象的属性
4、使用element.appendChild把它添加到容器里

后看代码

<!DOCTYPE html>
<html lang="cn">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>svg</title>
  <style>
    * {
      margin: 0px;
      padding: 0px;
    }

    .test {
      animation: appear 1s infinite;
      animation-iteration-count: 1;
      /* 应用结束时候的样式 */
      animation-fill-mode: forwards;
      opacity: 0;
    }


    @keyframes appear {
      0% {
        transform: scale(0.3);
        opacity: 0;
      }

      100% {
        transform: scale(1);
        opacity: 1;
      }
    }
  </style>
</head>

<body style="background-color: #999;">
  <div style="width: 100vw;height: 100vh;overflow: hidden;">
    <svg id="svgbox" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1960 1080">
      <defs>
        <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" style="stop-color:#DDD;stop-opacity:1" />
          <stop offset="100%" style="stop-color:#FFF;stop-opacity:1" />
        </linearGradient>
      </defs>
      <defs>
        <!-- 设边长为70,通过正弦余弦计算出个点的位置 -->
        <polygon id="a" points="37,0 107,0 142,60.2 107,120.4 37,120.4 2,60.2"
          style="fill:url(#grad1);stroke:#FFF;stroke-width:4" />
      </defs>
    </svg>
  </div>
</body>
<script>
  const svgbox = document.querySelector('#svgbox')
  const startY = 63.2
  const startX = 222
  const col = [5, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 2, 2, 1, 1, 1]
  svgbox.setAttribute('height', screen.availHeight)
  svgbox.setAttribute('width', screen.availWidth)
  for (let i = 0; i < 16; i++) {
    for (let j = 0; j < col[i]; j++) {
      // VG是基于XML格式定义图像的一种技术,因此创建节点的时候,需要指定命名空间
      const element = document.createElementNS('http://www.w3.org/2000/svg', 'use')
      const x = (j - 0.3) * startX + (i % 2 == 0 ? -(startX / 2) : 0)
      const y = (i - 1.1) * startY
      element.setAttribute('href', '#a')
      element.setAttribute('x', `${x}`)
      element.setAttribute('y', `${y}`)
      element.setAttribute('class', 'test')
      // 如不规定中心点,则根据svg整体做动画
      element.style.transformOrigin = `${x + 71}px ${y + 60.2}px`
      // 形成扩散的样式
      element.style.animationDelay = `${((i * 10 + j * 5) / 50).toFixed(1)}s`
      svgbox.appendChild(element)
    }
  }
</script>

</html>

PS:SVG是按元素的书写顺序进行堆叠的

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值