【问题标题】:How to apply SVG clipPath with CSS to one edge of div?如何将带有 CSS 的 SVG clipPath 应用到 div 的一个边缘?
【发布时间】:2021-07-01 10:07:06
【问题描述】:

我有一个布局,其中包含许多不同的曲线,可应用于全宽框的顶部和/或底部。我快到了,使用带有clipPathUnits="objectBoundingBox" 的SVG clipPath 元素,使用CSS clip-path: url(#curve) 应用于盒子。但是,目前曲线按比例缩放,我希望它在宽度随框缩放时保持其高度。

这是我当前的代码:

.box {

  height: 100vw;
  background-color: red;
  clip-path: url(#curve);

}
<div class="box"></div>

<svg>
    <defs>
        <clipPath id="curve" clipPathUnits="objectBoundingBox">
            <path d="M0 0.00880688C0 0.00880688 0.101517 -0.0152445 0.276014 0.0161458C0.474915 0.0519263 0.605365 0.0594333 0.727565 0.0493416C0.83584 0.0403992 1 0.0124763 1 0.0124763V1H0V0.00880688Z"/>
        </clipPath>
    </defs>
</svg>

我认为问题在于使用clipPathUnits="objectBoundingBox" 意味着虽然曲线总是从盒子的左边缘开始,并在右边缘结束(根据需要),但它的高度会随着盒子的高度而变化.我已将此处的高度设置为100vw,以便(几乎)看到这一点。我需要让路径从左到右(总是适合盒子),但从上到下我想要曲线路径覆盖的相同高度,无论盒子高度如何。我觉得我需要类似 clipPathUnits="objectBoundingBox" 的 X 轴,但 clipPathUnits="userSpaceOnUse" 的 Y。我认为这是不可能的,但我被困在另一种方法来解决这个问题。

【问题讨论】:

    标签: css svg clip-path


    【解决方案1】:

    将其用作掩码并将其宽度定义为100% 和auto 高度

    .box {
      height: 200px; /* this can be any height and it won't affect the curvature */
      -webkit-mask:
        url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 1 1"><path d="M0 0.00880688C0 0.00880688 0.101517 -0.0152445 0.276014 0.0161458C0.474915 0.0519263 0.605365 0.0594333 0.727565 0.0493416C0.83584 0.0403992 1 0.0124763 1 0.0124763V1H0V0.00880688Z" fill="black"/></svg>') 
        top/100% auto no-repeat;
      background:red;
    }
    &lt;div class="box"&gt;&lt;/div&gt;

    也可以考虑固定高度但需要使用preserveAspectRatio="none"

    .box {
      height: 200px; /* this can be any height and it won't affect the curvature */
      -webkit-mask:
        url('data:image/svg+xml;utf8,<svg preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 1 1"><path d="M0 0.00880688C0 0.00880688 0.101517 -0.0152445 0.276014 0.0161458C0.474915 0.0519263 0.605365 0.0594333 0.727565 0.0493416C0.83584 0.0403992 1 0.0124763 1 0.0124763V1H0V0.00880688Z" fill="black"/></svg>') 
        top/100% 1000px no-repeat;
        /*        ^--- adjust this like you want (at least bigger than the height) */
      background:red;
    }
    &lt;div class="box"&gt;&lt;/div&gt;

    【讨论】:

    • 非常好,非常感谢 - 出于某种原因,CSS 蒙版让我错过了。它们似乎更适合这个用例。
    • 注意:使用这种方法几乎可以到达那里,但是当盒子又高又窄时,遮罩形状的底部正在切断盒子底部的内容。我通过将:before 伪元素放入框中并对其应用蒙版来解决此问题(形状只是具有最小高度的曲线)。用一些 padding-top 来保持伪元素的比例,效果很好。
    • @SteveTaylor 你也可以考虑一个额外的遮罩层来覆盖底部,如下所示:jsfiddle.net/9pzg1cbd(你只需要找到最佳值[我在示例中使用的10vw]以确保以后与顶部没有间隙)
    猜你喜欢
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多