Javascript 如何在不损失性能的情况下不断移动SVG路径
我正在尝试做一个手机游戏,我画了6条SVG路径,然后不断地在屏幕上移动(从上到下)。我正在用一个简单的javascript操作路径,该javascript更新一些变量值,并使用它们设置路径的属性“d”。如以下示例所示:Javascript 如何在不损失性能的情况下不断移动SVG路径,javascript,html,performance,svg,mobile-browser,Javascript,Html,Performance,Svg,Mobile Browser,我正在尝试做一个手机游戏,我画了6条SVG路径,然后不断地在屏幕上移动(从上到下)。我正在用一个简单的javascript操作路径,该javascript更新一些变量值,并使用它们设置路径的属性“d”。如以下示例所示: setInterval(scrollPaths, 17); // ~ 60 fps function scrollPaths() { // leftYPoints is an array of points defined earlier and scrollSpeed
setInterval(scrollPaths, 17); // ~ 60 fps
function scrollPaths() {
// leftYPoints is an array of points defined earlier and scrollSpeed is an integer value (e.g. 2)
for (var i = 0; i < leftYPoints.length; i++) leftYPoints[i] += scrollSpeed;
// then I change the paths attribute
var pathAttribute = "M"+ leftXPoints[0] + leftYPoints[0]
+ " L" + leftXPoints[1] + leftYPoints[1];
document.getElementById("leftpath").setAttribute("d", pathAttribute);
document.getElementById("righpath").setAttribute("d", pathAttribute);
... // continue to do that with the other paths, changing some variables only
}
但不幸的是,结果不是很有效。javascript运行得快了一点,但路径的滞后效应仍然在发生。所以我在这里问:
var newYPos = 1;
var pathsGroup = document.getElementById("pathsgroup");
setInterval(scrollPaths, 17); // ~ 60 fps
function scrollPaths() {
// increased the position of the paths
newYPos += 1;
// then I did the transform of the paths with a group <g>
pathsGroup.setAttribute("transform", "translate(0," + value + ")");
}
var newYPos=1;
var pathsGroup=document.getElementById(“pathsGroup”);
setInterval(滚动路径,17);/~每秒60帧
函数滚动路径(){
//增加路径的位置
newYPos+=1;
//然后我和一组人一起变换路径
setAttribute(“转换”、“转换(0,+value+)”);
}
改进javascript代码是个好主意,但滞后效应根本没有改变,仍然很糟糕!谢谢阿基利斯米诺!也许让自己降低帧速率,直到一切都感觉足够灵敏?这是最奇怪的事情!我已经尝试过降低帧速率,这样路径会很慢地向下滚动,但有时它们仍然会有点“抖动”!嗯,我不知道,老兄,如果你能发布一些效果明显的工作代码,我很乐意为你看看。
var newYPos = 1;
var pathsGroup = document.getElementById("pathsgroup");
setInterval(scrollPaths, 17); // ~ 60 fps
function scrollPaths() {
// increased the position of the paths
newYPos += 1;
// then I did the transform of the paths with a group <g>
pathsGroup.setAttribute("transform", "translate(0," + value + ")");
}