优化交互式SVG JavaScript动画

时间:2017-01-14 03:46:32

标签: javascript css svg optimization svg-animate

我正在尝试使用JavaScript在Web浏览器中为SVG制作动画。我目前的方法是使用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>

我想确保我没有浪费太多资源,那么有没有什么方法在HTML文档/ JavaScript中资源消耗较少,以便使用SVG这样的受控交互式动画?

1 个答案:

答案 0 :(得分:2)

每次重新创建整个SVG效率极低。只需更新几何属性即可。

&#13;
&#13;
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);
&#13;
<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>
&#13;
&#13;
&#13;