调整窗口大小时的剪切路径与边界半径问题

时间:2018-12-31 04:18:15

标签: svg responsive clip-path

我想使用SVG作为clip-path来使图像的边缘变圆。是的,出于各种原因,我必须以这种方式进行操作。

问题: 调整浏览器窗口的大小时,由于我使用的是clipPathUnits="ObjectBoundingBox",所以形成圆角的点和句柄会根据图像的大小(边界框)进行调整。这会导致圆滑的边缘失去其“圆度”,并且看起来整体上非常糟糕。 CSS border-radius属性没有此问题。无论您如何调整浏览器窗口的大小,用border-radius剪切的div的边缘都不会松散其圆形。当您将浏览器窗口的大小调整为最窄或最宽的状态时,问题最明显。尝试使用此codepen,您会明白我的意思。顶部图像使用border-radius,底部图像使用clip-path。是否有任何方法可以强制SVG剪切路径的仅倒圆角边缘保持均等的倒圆角,无论如何在不牺牲剪切路径尺寸响应度的情况下调整图像大小?这有可能吗?如果有的话,我完全开放JavaScript解决方案。谢谢!

1 个答案:

答案 0 :(得分:2)

您可以欺骗<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>