![](/img/trans.png)
[英]How to rotate svg element in canvas without losing some part of it?
[英]How to constantly move SVG paths without losing performance
我正在嘗試做一個手機游戲,繪制6條SVG路徑,然后不斷在屏幕上(從上到下)移動。 我使用一個簡單的JavaScript操作路徑,該JavaScript更新了一些變量值並使用它們來設置路徑的屬性“ d”。 像下面的例子:
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本身運行非常快(scrollPaths每次大約需要5毫秒),並且可以在瀏覽器上完美運行。 但是,當我在移動瀏覽器中測試腳本時,路徑上似乎有很多滯后。 您會看到路徑滾動不流暢。 所以我試圖將scrollSpeed
的值減小到一個很小的值,但這並沒有解決。 因此,我認為問題與移動瀏覽器的渲染方法或類似問題有關。 我試圖找到一些答案,但沒有任何辦法解決我的問題。 然后,我在這里找到AmeliaBR的答案。 如何在不觸發緩慢重繪的情況下在網頁上移動SVG? 她說最好使用transform屬性,因為瀏覽器會理解它,因為它應該只移動一些已經渲染的內容,而不是重新計算整個布局。 所以我嘗試這樣做:
var newYPos = 1;
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>
document.getElementById("pathsgroup").setAttribute("transform", "translate(0," + value + ")");
}
但是不幸的是結果並不十分有效。 javascript運行得更快一些,但是路徑的滯后效應仍在發生。 所以我在這里,問:
不確定它是否有幫助,但是我在裝有Chrome的Nexus 5上進行了測試(應該有很好的性能)。
謝謝。
也許嘗試將“ pathsgroup”元素存儲為變量,這樣就不必每次迭代都繼續使用getElement了嗎?
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 + ")");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.