Skip to content
Advertisement

Transition effect between two states of svg polygon on hover

function menuHover(navLI, Y) {
    const topTriangle = navLI.querySelector(".triangle").querySelector("polygon");
    topTriangle.setAttribute("points", "0,0 200,0 100," + Y);
}

function navHoverIn(navLI) {menuHover(navLI, 60);}
function navHoverOut(navLI) {menuHover(navLI, 10);}
<div onmouseenter="navHoverIn(this)" onmouseleave="navHoverOut(this)">
  <svg viewBox="0 0 200 60" class="triangle">
    <polygon points="0,0 200,0 100,10">
  </svg>
</div>

If you hover over the triangle, the coordinate points of the polygon change. Any ideas what is the most convenient way to create the transition effect between the two states? So it doesn’t just instantly change, but has some kind of ease animation.

Advertisement

Answer

You can do all this in SMIL. No javascript required.

<div>
  <svg viewBox="0 0 200 60" class="triangle">
    <polygon points="0,0 200,0 100,10">
      <animate begin="mouseover" attributeName="points" to="0,0 200,0 100,60" dur="1s" restart="whenNotActive" fill="freeze"/>
      <animate attributeName="points" begin="mouseout" dur="1s" fill="freeze" restart="whenNotActive" to="0,0 200,0 100,10"/>
    </polygon>
  </svg>
</div>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement