悬停时对 SVG 进行动画处理 - 在悬停时通过点制作微笑

Yor*_*nov 0 javascript css svg svg-animate

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

过渡必须平稳。

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

在此输入图像描述

谢谢

ccp*_*rog 6

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

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

#line {
  fill: none;
  stroke: black;
  stroke-width: 4;
  stroke-dasharray: 0 1;
  stroke-linecap: round;
}
#overlay {
  opacity: 0;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)