2016-09-28 202 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>