HTML Animations using SVG

A basic animation test using the HTML SVG element instead of the CANVAS. This one uses the svg.js library. This library has it’s own, built in animation function that is used to make the red rectangle move back and forth (1 second period).

The green circle is moved using the requestAnimationFrame function with some coding to make it bounce back and forth.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <script src='./svg.js/svg.min.js'></script>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="svgPlace"></div>
  </body>

  <script type="text/javascript">
    var draw = SVG().addTo('#svgPlace').size(300,400);
    var line = draw.line([[20,20],[200,20]]).stroke({width: 1, color:'#f00'});

    //Metronome red rectangle.
    rect = draw.rect(50,100).move(200,20).fill('#f00');
    rect.radius(10);
    dir = 'left';

    setInterval(animate, 1000);
    function animate(){
      if (dir === 'left'){
        px = 20;
        py = 20;
        dir = "right";
      }
      else {
        px = 200;
        py = 20;
        dir = "left";
      }
      rect.animate({
        duration: 1000,
        when: 'now'
      }).move(px,py);
    }

    //Green circle
    circ = draw.circle(20).fill('#0f0').move(250,10);
    window.requestAnimationFrame(animateCirc);
    cx = 250;
    cy = 20;
    dy = 1;

    function animateCirc(){
      cy+=dy;
      circ.move(cx,cy);
      window.requestAnimationFrame(animateCirc);
      if (cy > 100 ){
        cy = 100;
        dy = -dy;
      } else if (cy < 20) {
        cy = 20;
        dy = -dy;
      }
    }

  </script>
</html>

Leave a Reply