【问题标题】:Fill SVG path with colour but on hover fade-in pattern用颜色填充 SVG 路径,但使用悬停淡入模式
【发布时间】:2017-09-23 00:26:58
【问题描述】:

我正在尝试添加 SVG 图像(在本例中为比利时国旗)作为 SVG 路径(实际上是椭圆)的填充。悬停时,椭圆的填充必须变为红色。换句话说,填充 SVG 必须“淡出”。我尝试了一种使用 CSS 的方式,但 SVG 模式和过渡似乎都不起作用。我在 Chrome 和 Firefox 上试过。

svg ellipse {
  fill: url(#img1);
  transition: fill 400ms;
}

svg:hover ellipse {
  fill: red;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events" version="1.1" height="480" width="640" viewBox="0 0 640 480">
  <defs>
    <pattern x="0" y="0" id="img1" height="480" width="640" viewBox="0 0 640 480">
        <g fill-rule="evenodd" stroke-width="1pt">
          <path d="M0 0h213.335v479.997H0z" />
          <path fill="#ffd90c" d="M213.335 0H426.67v479.997H213.335z" />
          <path fill="#f31830" d="M426.67 0h213.335v479.997H426.67z" />
        </g>
    </pattern>
  </defs>
  <rect fill="none" stroke="blue" x="1" y="1" width="640" height="480"/>
  <ellipse stroke="black" stroke-width="5" cx="400" cy="200" rx="350" ry="150" />
</svg>

【问题讨论】:

标签: css svg css-transitions


【解决方案1】:

你不能像那样过渡fill,因为这两个填充不是可以在它们之间平滑插值的东西。

您需要做的是有两个版本的椭圆,一个在另一个之上。然后淡入或淡出顶部。

.visible-on-hover {
  transition: opacity 400ms;
  opacity: 0;
}

.visible-on-hover:hover {
  opacity: 1;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events" version="1.1" height="480" width="640" viewBox="0 0 640 480">
  <defs>
    <pattern x="0" y="0" id="img1" height="1" width="1"
             viewBox="0 0 640 480" preserveAspectRatio="xMidYMid slice">
        <g fill-rule="evenodd" stroke-width="1pt">
          <path d="M0 0h213.335v479.997H0z" />
          <path fill="#ffd90c" d="M213.335 0H426.67v479.997H213.335z" />
          <path fill="#f31830" d="M426.67 0h213.335v479.997H426.67z" />
        </g>
    </pattern>
  </defs>
  <rect fill="none" stroke="blue" x="1" y="1" width="640" height="480"/>
  <ellipse stroke="black" stroke-width="5" cx="400" cy="200" rx="350" ry="150" fill="url(#img1)"/>
  <ellipse stroke="black" stroke-width="5" cx="400" cy="200" rx="350" ry="150" fill="red" class="visible-on-hover"/>
</svg>

【讨论】:

  • 不过,我还有一个问题。为什么图案的宽度/高度指定为1?使用fill时,会自动覆盖整个路径吗? (类似于background-size: cover 的工作原理?)
  • 这些属性(x,y,width,height)的默认坐标空间是patternUnits="objectBoundingBox"。这意味着它们是相对于元素的边界框的。 (0,0) 是元素的左上角; (1,1) 是元素的右下角。 See the SVG spec section on Patterns.
猜你喜欢
  • 2021-03-13
  • 2013-07-23
  • 2015-06-02
  • 1970-01-01
  • 2021-07-05
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多