Home > OS >  How to make a line in svg vibrate (oscillation move)
How to make a line in svg vibrate (oscillation move)

Time:07-15

Let's suppose we do have a simple svg file like this:

<svg height="1000" width="1000">
  <line x1="10" y1="50" x2="250" y2="50"  stroke="black" stroke-width="3" fill="red" />
  <circle cx="270" cy="50" r="20" stroke="black" stroke-width="3" fill="red" />
</svg>

Which gives us a line with and circle, I want to vibrate the line the circle (an oscillation, I'm not sure if that word is correct, like if winds make it move), so it gives the graph a life.

How can I do a such animation please ?

CodePudding user response:

As a starting point you may need to

  1. transform the line in a path with a line written as a cubic bezier

  2. calculate 2 other paths as the position and shape of the bented curve up and down

  3. In this case I'm adding a simple SMIL animation betwin the 3 variants of the curve.

4.the circle's center is corresponding to the ending point of the curve. Alternatively you may want to use a marker instead.

You can elaborare starting from this idea.

<svg viewBox="0 -50 300 200" width="300"> 
  <path stroke="black" stroke-width="3" fill="red"  d="M10,50C100,50 200,50 250,50">
    <animate 
       attributeName="d"
       values="M10,50C100,50 200,50 250,50;
               M10,50C100,50 200,50 248,80;
               M10,50C100,50 200,50 250,50;
               M10,50C100,50 200,50 248,20; 
               M10,50C100,50 200,50 250,50;"
       dur="5s"
       repeatCount="indefinite"/>
  </path>
   
  <circle cx="250" cy="50" r="20" stroke="black" stroke-width="3" fill="red" >
    <animate 
       attributeName="cx"
       values="250;248;250;248;250"
       dur="5s"
       repeatCount="indefinite"/>
     <animate 
       attributeName="cy"
       values="50;80;50;20;50"
       dur="5s"
       repeatCount="indefinite"/>
  </circle>
</svg>

  • Related