Question

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.

Was it helpful?

Solution

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/

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top