Search code examples
javascriptcsssvgoptimizationsvg-animate

Optimizing Interactive SVG JavaScript Animation


I am trying to animate SVG's in a web browser using JavaScript. My current methodology is using innerHTML:

var e = new entity();

function draw() {
  element = document.getElementById("canvas");
  e.radius += .1;
  e.pos[0] += .1; e.pos[1] += .1;
  var insides = "";
  insides += '<svg height="80%" viewBox="0 0 100 100">' + e.show() + '</svg>';
  element.innerHTML = insides;
}

function entity() {
  this.pos = [0, 0];
  this.radius = 1;
  this.show = function() {
    return '<circle cx="' + String(this.pos[0]) + '" cy="' + String(this.pos[1]) + '" r="' + String(this.radius) + '" />';
  }
}
window.setInterval(draw, 60);
<div id="canvas" style="text-align:center;"></div>

I want to make sure I am not wasting too many resources, so are there any ways that are less resource-intensive in the HTML document/JavaScript to do controlled interactive animations with SVG's such as this?


Solution

  • Recreating the whole SVG every time is extremely inefficient. Just update the geometry attributes.

    var e = new entity();
    
    function draw() {
      element = document.getElementById("canvas");
      e.radius += .1;
      e.pos[0] += .1; e.pos[1] += .1;
      e.show();
    }
    
    function entity() {
      this.element = document.getElementById("mycircle");
      this.pos = [0, 0];
      this.radius = 1;
      this.show = function() {
        this.element.cx.baseVal.value = this.pos[0];
        this.element.cy.baseVal.value = this.pos[1];
        this.element.r.baseVal.value = this.radius;
      }
    }
    
    window.setInterval(draw, 60);
    <div id="canvas" style="text-align:center;">
      <svg height="80%" viewBox="0 0 100 100">
        <circle id="mycircle" cx="0" cy="0" r="0" />
      </svg>
    </div>