gpt4 book ai didi

javascript - 优化交互式 SVG JavaScript 动画

转载 作者:行者123 更新时间:2023-11-30 15:35:21 24 4
gpt4 key购买 nike

我正在尝试使用 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 制作受控的交互式动画,例如这样?

最佳答案

每次都重新创建整个 SVG 非常低效。只需更新几何属性。

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>

关于javascript - 优化交互式 SVG JavaScript 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41646608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com