【问题标题】:How to apply SVG clip path relative to origin SVG instead of target element如何应用相对于原始 SVG 而不是目标元素的 SVG 剪辑路径
【发布时间】:2017-12-09 01:27:48
【问题描述】:

我正在尝试将 SVG clipPath 应用到具有固定定位的单独背景 div。我希望 clip-path 保持在原始 SVG 元素的确切位置,并在滚动(或以其他方式转换)时相应地移动。

相反,剪辑路径是相对于目标元素的原点插入的,并且丢失了所有定位、滚动和变换。有没有办法保留原始属性并将它们应用于单独的 div?

在下面嵌入的 sn-p 中,蓝色圆圈是我希望 clip-path 出现的位置,而红色圆圈是它出现的位置。

#container {
  clip-path: url(#myClip);
  position: fixed;
  width: 100vw;
  height: 100vh;
  background-color: red;
}

#offset-container {
  position: absolute;
  top: 200px;
  left: 200px;
  width: 200px;
  height: 200px;
  border-style: solid;
  border-color: blue;
}
<div id='container'>

</div>

<div id='offset-container'>
  <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <clipPath id="myClip">
      <circle cx="50%" cy="50%" r="50%"/>
    </clipPath>
  </defs>
  <circle cx="50%" cy="50%" r="50%" fill='blue' fill-opacity='0.5'/>
</svg>
</div>

JSFiddle:https://jsfiddle.net/shongololo/pa0qLs45/1/

【问题讨论】:

    标签: javascript css svg clip-path


    【解决方案1】:

    这在 Firefox 中(几乎)有效,但在 Chrome 中无效,它显示了一个非常奇怪的错误。

    您将需要两个 div:外部是相对定位的,并定义了剪辑路径,因此它可以移动。内部定位固定。显然,需要显式设置top/left/width/height,然后引用视口坐标。

    body { margin: 0 }
    
    #container {
      position: relative;
      overflow: hidden;
      top: 202px; /* border! */
      left: 202px;
      clip-path: url(#myClip);
      width: 200px;
      height: 200px;
    }
    
    #fixed {
      position: fixed;
      top: 0px;
      left: 0px;
      width: 100vw;
      height: 100vh;
      background-color: red;
    }
    
    #offset-container {
      position: absolute;
      top: 200px;
      left: 200px;
      width: 200px;
      height: 200px;
      border: 2px solid blue;
    }
    <div id='container'>
        <div id="fixed"></div>
    </div>
    
    <div id='offset-container'>
      <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <clipPath id="myClip">
          <circle cx="50%" cy="50%" r="50%"/>
        </clipPath>
      </defs>
      <circle cx="50%" cy="50%" r="50%" fill='blue' fill-opacity='0.5'/>
    </svg>
    </div>

    【讨论】:

    • 非常有趣。 Chrome中确实存在奇怪的错误。 Safari 似乎完全忽略了剪辑路径!
    猜你喜欢
    • 2018-10-29
    • 2019-01-02
    • 2016-03-31
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2020-08-22
    • 2015-07-02
    • 2019-09-25
    相关资源
    最近更新 更多