剪切路径svg适用于图像,但不适用于div

问题描述 投票:1回答:2

在MDN上,有一个有关如何在图像上使用剪切路径svg的示例。相同的剪切路径似乎不适用于div元素。有人可以澄清一下:

  • 为什么此代码无法按预期工作
  • 使svg剪辑路径在div上工作的方法

裁剪图像的示例代码(based on MDN docs

#clipped {
  clip-path: url(#cross);
}
<img id="clipped" src="https://mdn.mozillademos.org/files/12668/MDN.svg"
    alt="MDN logo">
<svg height="0" width="0">
  <defs>
    <clipPath id="cross">
      <rect y="110" x="137" width="90" height="90"/>
      <rect x="0" y="110" width="90" height="90"/>
      <rect x="137" y="0" width="90" height="90"/>
      <rect x="0" y="0" width="90" height="90"/>
    </clipPath>
  </defs>
</svg>

div上的相同剪切路径(似乎不起作用)

#clipped {
  width: 100px;
  height: 100px;
  background: black;
  clip-path: url(#cross);
}
<div id="clipped"></div>
<svg height="0" width="0">
  <defs>
    <clipPath id="cross">
      <rect y="110" x="137" width="90" height="90"/>
      <rect x="0" y="110" width="90" height="90"/>
      <rect x="137" y="0" width="90" height="90"/>
      <rect x="0" y="0" width="90" height="90"/>
    </clipPath>
  </defs>
</svg>
css svg clip-path
2个回答
0
投票

正如@enxaneta指出的,这全都取决于大小。如果增加div的大小,则会看到效果:

#clipped {
  width: 300px;
  height: 200px;
  background: black;
  clip-path: url(#cross);
}
<div id="clipped"></div>
<svg height="0" width="0">
  <defs>
    <clipPath id="cross">
      <rect y="110" x="137" width="90" height="90"/>
      <rect x="0" y="110" width="90" height="90"/>
      <rect x="137" y="0" width="90" height="90"/>
      <rect x="0" y="0" width="90" height="90"/>
    </clipPath>
  </defs>
</svg>

或者您可以使用遮罩使动态内容:

.box {
  width: 100px;
  height: 100px;
  margin:5px;
  background: linear-gradient(red,blue);
  -webkit-mask:
    linear-gradient(white,white) top left,
    linear-gradient(white,white) top right,
    linear-gradient(white,white) bottom left,
    linear-gradient(white,white) bottom right;
  -webkit-mask-size:40% 40%;
  -webkit-mask-repeat:no-repeat;
  -mask:
    linear-gradient(white,white) top left,
    linear-gradient(white,white) top right,
    linear-gradient(white,white) bottom left,
    linear-gradient(white,white) bottom right;
  mask-size:40% 40%;
  mask-repeat:no-repeat;
}
<div class="box"></div>

<div class="box" style="width:200px;height:200px;"></div>

-1
投票

Clip-path不被继承。Establishing a new clipping path: the ‘clipPath’ elementW3C

因此,通过将clip-path应用于父块,我们将不会获得剪切的子元素

[最好使用svg <image>标记而不是<img>并对其应用clip-path

使用div作为自适应容器

.wrapped {
width:25%;
height:25%;
}
#img1 {
clip-path:url(#cross);
}
<div class="wrapped">
<svg  viewBox="0 0 250 250">
  <defs>
    <clipPath id="cross">
      <rect y="110" x="137" width="90" height="90"/>
      <rect x="0" y="110" width="90" height="90"/>
      <rect x="137" y="0" width="90" height="90"/>
      <rect x="0" y="0" width="90" height="90"/>
    </clipPath>
  </defs> 

<image id="img1" width="100%" height="100%" xlink:href="https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg"/>

</svg> 

</div>
© www.soinside.com 2019 - 2024. All rights reserved.