Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use CSS transitions on SVG attributes? Like y2 on a line?

Tags:

css

reactjs

svg

I want to change the attributes of an SVG line, and animate the transition to the new coordinates.

I am using reactjs to change the value of y2 in this example:

<line stroke='green' x1='0' y1='50%' x2='100%' y2='25%'>

to

<line stroke='green' x1='0' y1='50%' x2='100%' y2='75%'>

with CSS like

.myStuff * {
    transition: all 1s;
}

Is it possible for a CSS transition to work on the y2 attribute? Or is there a way to set the attributes of the line in CSS like:

.myStuff line {
    y2: 25%;
}

(which I know doesn't work)

I have considered using javascript, but that adds complexity

I have considered using SMIL, but I would have to store the old and new y2 states, and I don't think reactjs allows the animate element.

I have considered using a transform on my line element, and will go down this path if I can't find a better solution. I want to avoid the math and complexity.

like image 791
brendangibson Avatar asked Aug 18 '15 14:08

brendangibson


1 Answers

Using JQuery .attr() changes "y2" to "75%" like you see in fiddle 1

But the hard part is you want to use transition.

In this case you have to use transform:matrix():

HTML:

<svg height="300" width="300">
  <line class="first" stroke='green' x1='0' y1='50%' x2='100%' y2='25%'/>
</svg>

<button id="change">change</button>

JQuery:

$(document).ready(function(){
   $("#button").click(function(){
      $(".first").css({
                    "transform":"matrix(1, 0.6, 0, 1, 0, 0)",
                    "-webkit-transform":"matrix(1, 0.6, 0, 1, 0, 0)",
                    "-ms-transform":"matrix(1, 0.6, 0, 1, 0, 0)"
     });
   });    
});

CSS:

.first
{
    -webkit-transition-duration: 1s; /* Safari */
    transition-duration: 1s;
}

See a working fiddle 2.

The tip is using some numbers in matrix() which provides your result.

like image 170
eylay Avatar answered Sep 21 '22 06:09

eylay