`clip-path` 如何绘制圆角平行四边形呢?

作者站长头像
站长
· 阅读数 7
 .polygon-box {
            width: 192px;
            height: 65px;
            background-color: #8D8D8D;
            clip-path: polygon(0px 0px, 8px 65px, 192px 65px, 184px 0px);
        }

clip-path 这样绘制的是非圆角的平行四边形!`clip-path` 如何绘制圆角平行四边形呢?

回复
1个回答
avatar
test
2024-07-01

https://jsrun.net/4HFKp

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>圆角平行四边形-基于clip-path path函数实现</title>
  <style>
    ul {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }

    li {
      border: 1px solid black;
      list-style: none;
    }

    .polygon {
      width: 200px;
      height: 100px;
      background-color: #ddd;
      clip-path: path('M 0,0 H 150 L 200, 100 H 50 Z');
    }
  </style>
</head>

<body>
  <ul>
    <li>
      <div class="polygon polygon1"></div>
    </li>
    <li>
      <div class="polygon polygon2"></div>
    </li>
    <li>
      <div class="polygon polygon3"></div>
    </li>
    <li>
      <div class="polygon polygon4"></div>
    </li>
  </ul>

  <script>
    function setPath(element, pw, len) {
      // pw 四边形宽度
      // len 圆角起始点距离矩形定点距离
      const rect = element.getBoundingClientRect();
      const width = rect.width;
      const height = rect.height;

      pw = pw || width * .8
      len = len || 10

      const angle = Math.atan(height / (width - pw));
      const degree = angle * (180 / Math.PI);
      const dx = len * Math.cos(angle)
      const dy = len * Math.sin(angle)

      // x0 y0 平行四边形顶点坐标;x y 圆角起始点左边
      var dot1 = { x0: 0, y0: 0, x: dx, y: dy, }
      var dot2 = { x0: 0, y0: 0, x: len, y: 0, }
      var dot3 = { x0: pw, y0: 0, x: pw - len, y: 0, }
      var dot4 = { x0: pw, y0: 0, x: pw + dx, y: dy, }
      var dot5 = { x0: width, y0: height, x: width - dx, y: height - dy, }
      var dot6 = { x0: width, y0: height, x: width - len, y: height, }
      var dot7 = { x0: width - pw, y0: height, x: width - pw + len, y: height, }
      var dot8 = { x0: width - pw, y0: height, x: width - pw - dx, y: height - dy, }

      var path = `M ${dot1.x},${dot1.y} S ${dot2.x0},${dot2.y0} ${dot2.x},${dot2.y} L ${dot3.x},${dot3.y} S ${dot4.x0},${dot4.y0} ${dot4.x},${dot4.y} L ${dot5.x},${dot5.y} S ${dot6.x0},${dot6.y0} ${dot6.x},${dot6.y} L ${dot7.x},${dot7.y} S ${dot8.x0},${dot8.y0} ${dot8.x},${dot8.y} Z`

      // path拼接完成,既可以在css的clip-path: path()中使用,也可以在svg path标签d属性中使用

      element.style.clipPath = `path('${path}')`;
    }

    setPath(document.querySelector('.polygon1'), 140, 0)
    setPath(document.querySelector('.polygon2'), 140, 20)
    setPath(document.querySelector('.polygon3'), 140, 40)
    setPath(document.querySelector('.polygon4'))
  </script>
</body>

</html>
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容