【问题标题】:Clip-Path vs Border-Radius issue when window is resized调整窗口大小时的 Clip-Path vs Border-Radius 问题
【发布时间】:2019-05-27 18:07:06
【问题描述】:

我想使用 SVG 作为clip-path 来圆化图像的边缘。是的,出于各种原因,我必须这样做。

问题: 当浏览器窗口调整大小时,形成圆角的点和句柄会根据图像(边界框)的变化大小进行调整,因为我使用的是clipPathUnits="ObjectBoundingBox"。这会导致圆形边缘失去其“圆度”,整体看起来非常糟糕。 CSS border-radius 属性没有这个问题。无论您如何调整浏览器窗口的大小,使用border-radius 裁剪的 div 的边缘都不会失去其圆形形状。当您将浏览器窗口调整到最窄或最宽的状态时,问题最为明显。试试这个codepen,你就会明白我的意思了。上图使用border-radius,下图使用clip-path。是否有任何方法可以强制 SVG 剪辑路径的唯一圆形边缘保持相同的圆形,无论如何调整图像大小而不牺牲剪辑路径尺寸的响应性?这甚至可能吗?如果有 JavaScript 解决方案,我完全愿意接受。谢谢!

【问题讨论】:

    标签: svg responsive clip-path


    【解决方案1】:

    您可以欺骗<svg> 元素使其具有与图像相同的尺寸,然后使用相对单位调整剪辑路径的大小。缺点是您不能重复使用这些路径,而必须为每个单独的图像定义一个。

    .box {
      left: 5%;
      height: 40%;
      position: absolute;
      background-color: blue;
      overflow: hidden;
    }
    #box1 {
      top: 5%;
      width: 50%;
      clip-path: url(#clipPath1);
    }
    #box2 {
      top: 55%;
      width: 90%;
      clip-path: url(#clipPath2);
    }
    
    .flower{
      width: 100%;
      height: 100%;
      object-fit: cover;
      object-position: center;
    }
    
    svg {
      width: 100%;
      height: 100%;
      position: absolute;
    }
    <div class="box" id="box1">
        <img class="flower" src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="none">
        <svg>
            <clipPath id="clipPath1" clipPathUnits="userSpaceOnUse">
                <rect width="100%" height="100%" rx="20" ry="20"/>
          </clipPath>
        </svg>
    </div>
    <div class="box" id="box2">
        <img class="flower" src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="none">
        <svg>
            <clipPath id="clipPath2" clipPathUnits="userSpaceOnUse">
                <rect width="100%" height="100%" rx="20" ry="20"/>
          </clipPath>
        </svg>
    </div>

    【讨论】:

    • 漂亮!似乎它的工作。从来没想过。谢谢!
    猜你喜欢
    • 2011-09-26
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多