Animated line graph in Javascript?

Jonathan picture Jonathan · Jun 5, 2009 · Viewed 11.5k times · Source

I'd like to do a line-graph on a web-page using Javascript. I want it to be animated so that when the page loads, the line is slowly "drawn" onto the graph.

I've managed to get a static graph working, using flot, however I'm unsure how to animate it.

It would be half my job done to just make it draw a line half-way along the graph, but when I try to do this by modifying the data-set, it modifies the structure of the graph as well, so that the line fills 100% of the graph area.

So is there a way to draw the line data in stages, so I can animate it?

Or alternatively, is there some other javascript graphing framework that I've overlooked?

Answer

Jose Basilio picture Jose Basilio · Jun 5, 2009

Here's a simple example using Flot

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples</title>
<link href="layout.css" rel="stylesheet" type="text/css"></link>
<!--[if IE]><script language="javascript" type="text/javascript" src="../excanvas.pack.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../jquery.flot.js"></script>
</head>
<body>
<h1>Animated Flot Example</h1>
<div id="placeholder" style="width:600px;height:300px;"></div>
<script id="source" language="javascript" type="text/javascript">
$(function () {
    var linePoints = [[0, 3], [4, 8], [8, 5], [9, 13]];
    var i = 0;
    var arr = [[]];
    var timer = setInterval(function(){
     arr[0].push(linePoints[i]);
     $.plot($("#placeholder"), arr);
     i++;
     if(i === linePoints.length)
        clearInterval(timer);
    },300);
});
</script>
 </body>
</html>