2016-09-28 63 views
0

我試圖調用.attrTween()來平滑地動畫對象的y屬性。d3.attrTween()不能流暢地動畫

下面是我使用的代碼:https://jsbin.com/ceronufuha/edit?html,js,output

(當然這是一個過於簡單化的例子)

:如果你想看看

let svg = d3.select('svg') 

svg.append('text') 
    .attr({ x: 100, y: 100 }) 
    .text('I should be animated smoothly') 

// animate consecutively through all positions 
let positions = [10, 20, 15, 35, 70, 50, 30, 10, 30, 45] 

svg.transition() 
    .duration(10000) 
    .ease('linear') 
    .selectAll('text') 
    .attrTween('y', function() { 
    return function(t) { 
     return positions[Math.floor(t * 10)] 
    } 
    }) 

這裏的jsfiddle

爲什麼動畫不平滑,我錯過了什麼?

回答

3

您的代碼不會平滑,因爲它的值之間不會有​​。在每個勾號上,您基本上都會找到一個索引並「跳躍」到它。如果您想要在10秒鐘內在每個值之間進行動畫製作,您需要像下面這樣編寫它。我正在使用.transition()...attr(),它會在當前y值和下一個y值之間自動創建插值。

let svg = d3.select('svg') 
 

 
let text = svg.append('text') 
 
    .attr({ x: 100, y: 100 }) 
 
    .text('I should be animated smoothly') 
 

 
let positions = [10, 20, 15, 35, 70, 50, 30, 10, 30, 45] 
 

 
nextMove(0); 
 

 
function nextMove(i){ 
 
    text.transition() 
 
    .duration(10000/positions.length) 
 
    .ease('linear') 
 
    .attr('y', positions[i]) 
 
    .each('end', function(){ 
 
     i += 1; 
 
     if (i < positions.length){ 
 
     nextMove(i); 
 
     } 
 
    }); 
 
}
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width"> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script> 
 
    <title>JS Bin</title> 
 
</head> 
 
<body> 
 
    <svg height="400" width="400"></svg> 
 
</body> 
 
</html>