-2

I am trying to draw an animated line inside an SVG element. i.e the line draws over a period of time.

I've searched, but all answers usually point to Raphael library. I however, cannot use any libraries available on the internet.

Need some pointers on where to start.

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239

2 Answers2

4

I've never, ever worked with SVG in my live, yet in 10 minutes after a quick google I came up with:

<svg width=200 height=200>
    <line id="myLine" x1="5" y1="10" x2="5" y2="10" stroke-width=".5" stroke="red"/>
</svg>
<script>
var line = document.getElementById('myLine');
var count = 0;
var interval = window.setInterval(function() {
    line.setAttribute('y2', 2 + +line.getAttribute('y2'));
    line.setAttribute('x2', 1 + +line.getAttribute('x2'));
    if (count++ > 75)
        window.clearInterval(interval);
}, 100);
</script>

See: http://jsfiddle.net/YSmDH/

RoToRa
  • 37,635
  • 12
  • 69
  • 105
0

You should use the <canvas id='mycanvas' width='300' height='300' /> element and draw your line like this:

function drawShape(){
  // get the canvas element using the DOM
  var canvas = document.getElementById('mycanvas');

  // Make sure we don't execute when canvas isn't supported
  if (canvas.getContext){

   // use getContext to use the canvas for drawing
   var ctx = canvas.getContext('2d');

   // Stroked triangle
   ctx.beginPath();
   ctx.moveTo(125,125);
   ctx.lineTo(125,45);
   ctx.lineTo(45,125);
   ctx.closePath();
   ctx.stroke();

  }
}

By adding a timeout and clearing your 2D-Context and afterwards creating it new, you can animate your line

This is a very good tutorial for canvas manipulation.

Jan Hommes
  • 5,122
  • 4
  • 33
  • 45