Search code examples
animationsvgopacity

using svg animation reducing the opacity of a rectangle when clicking on the rectangle


I need to change the opacity(from 1 to 0) of the rectangle when clicking on the rectangle.This is the code I used.But I am not able to change the opacity of the rectangle.If anyone knows please help me.

<svg height="800px" width="1100px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <rect id="rect1" x="263" y="87.5" width="100" height="25" fill="#F67F33" style="stroke:black;stroke-width:1">
     <animate xlink:href="#rect1" attributeName="opacity" from="1" to="0" begin="click" fill="freeze" />
  </rect>
</svg>

Solution

  • You have no duration for the animation. Also if animate is a child of the element is is applied to no xlink:href is required.

    <svg height="800px" width="1100px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <rect x="263" y="87.5" width="100" height="25" fill="#F67F33" style="stroke:black;stroke-width:1">
         <animate attributeName="opacity" from="1" to="0" dur="3s" begin="click" fill="freeze" />
      </rect>
    </svg>

    If you want the animation to be instantaneous, you can use set

    <svg height="800px" width="1100px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <rect x="263" y="87.5" width="100" height="25" fill="#F67F33" style="stroke:black;stroke-width:1">
         <set attributeName="opacity" to="0" begin="click" fill="freeze" />
      </rect>
    </svg>