首页 > 解决方案 > 悬停时动画 SVG - 悬停时不要做微笑

问题描述

我有一个 SVG 文件,其中点在直线上。我想要实现的是当用户将鼠标悬停在 svg 文件上时,点会变成像附加图像一样的微笑。

过渡需要平稳。

这里最好的方法是什么?我可以只使用 css 还是我也应该使用 js?

在此处输入图像描述

谢谢

标签: javascriptcsssvgsvg-animate

解决方案


使用SMIL 动画,无需任何脚本即可实现。它将三次贝塞尔路径从直线变为弯曲并返回。动画由位于线条顶部的透明矩形上的事件mouseover触发。mouseout

该行本身使用了两个小技巧的组合:您可以将 a 设置pathLength为属性,stroke-dasharray然后根据它计算破折号长度。对于 astroke-dasharray: 0 1与 的组合stroke-linecap,长度为零的破折号显示为点,笔划宽度为它们的直径。只需使用pathLengthstroke-width更改点的距离及其大小即可。

#line {
  fill: none;
  stroke: black;
  stroke-width: 4;
  stroke-dasharray: 0 1;
  stroke-linecap: round;
}
#overlay {
  opacity: 0;
}
<svg viewBox="0 0 100 100" width="150">
  <path id="line" d="M 10 50 C 35 50 65 50 90 50" pathLength="15">
    <animate attributeName="d" begin="overlay.mouseover" dur="0.3s"
             fill="freeze" restart="whenNotActive"
             from="M 10 50 C 35 50 70 50 90 50"
             to="M 15 30 C 20 70 80 70 85 30"/>
    <animate attributeName="d" begin="overlay.mouseout" dur="0.3s"
             fill="freeze" restart="whenNotActive"
             from="M 15 30 C 20 70 80 70 85 30"
             to="M 10 50 C 35 50 65 50 90 50"/>
  </path>
  <rect id="overlay" width="100%" height="100%" />
</svg>


推荐阅读