Search code examples
jquerysvgjquery-svg

SVG line chart using pure javascript/jquery animation


I have created one SVG line chart. Please refer below screenshot.

enter image description here

Refer below SVG element for line chart.

<svg>
-------------------------------------------------------------
<path id="Ram" fill="none" stroke-width="3" stroke="url(#container_Ram1Gradient)" stroke-linecap="butt" stroke-linejoin="round" d="M 142.8 90.51999999999998 L 213.6 371.32 M 213.6 371.32 L 284.4 306.52 M 284.4 306.52 L 355.2 241.71999999999997 M 355.2 241.71999999999997 L 426 163.96000000000004 M 426 163.96000000000004 L 496.8 224.44000000000003 M 496.8 224.44000000000003 L 567.5999999999999 129.39999999999998 M 567.5999999999999 129.39999999999998 L 638.4 202.83999999999997 M 638.4 202.83999999999997 L 709.2 215.8 " clip-path="url(#ChartAreaClip)"/>
-------------------------------------------
</svg>

i want to perform animation in that line chart. that means the line chart will be displayed dynamically / it will draw on run time.

Please refer below link.

http://www.highcharts.com/demo/

i dont want to use <animate> and <animateMotion> or any thing related SVG animation . because some animation not working in all the browsers.

so i want to perform pure jquery animation (i.e using jquery.animate method). how can i create or apply the animation in line chart using jquery animate method or any other way ?

Thanks,

Siva


Solution

  • First you can store your data in an json object:

    {
        "John": [
            {
                "x": 142.8,
                "y": 90.52
            },
            {
                "x": 213.6,
                "y": 371.32
            }
        ]
    }
    

    The svg path will be something like this:

    <path id="Ram" fill="none" stroke-width="3" stroke="url(#container_Ram1Gradient)" stroke-linecap="butt" stroke-linejoin="round" d="" clip-path="url(#ChartAreaClip)"/>
    

    Now you have to fill the path with javascript/jquery with something like this:

    var counter = 0;
    
    function addPoint(x, y, isFirst){
        var new_point = (isFirst? " M " : " L ")+x+" "+y;
        $('#Ram').attr("d", $('#Ram').attr("d")+""+new_point);
        counter++;
        if(counter < John.length){
            setTimeout(addPoint(John[counter].x, John[counter].y, false),200); // Add a new point after 200 milliseconds
        }
    }
    
    addPoint(John[0].x, John[0].y, true);