3

我正在使用 paper.js 并且我正在尝试沿着我创建的路径为项目设置动画......

//Path : 
 path = new Path();
 path.add(new Point(0,100), new Point(120,100), new Point(120,150));
//Item
 circle = new Path.Circle(0,100,4);
 circle.strokeColor = "#EEE";

在制作动画时(使用 onFrame()),我希望圆圈跟随路径......有谁知道该怎么做?我没有在文档或谷歌上找到它..我希望它足够清楚..

感谢您的回答!

4

4 回答 4

4

还没有测试它,但它应该是这样的。

// vars
var point1 = [0, 100];
var point2 = [120, 100];
var point3 = [120, 150];

// draw the line
var path = new Path();
path.add(new Point(point1), new Point(point2), new Point(point3));
path.closed = true;

// draw the circle
var circle = new Path.Circle(0,100,4);
circle.strokeColor = "#EEE";

// target to move to
var target = point2;

// how many frame does it take to reach a target
var steps = 200;

// defined vars for onFrame
var dX       = 0;
var dY       = 0;

// position circle on path
circle.position.x = target[0];
circle.position.y = target[1];

function onFrame(event) {

    //check if cricle reached its target
    if (Math.round(circle.position.x) == target[0] && Math.round(circle.position.y) == target[1]) {
        switch(target) {
            case point1:
                target = point2;
                break;
            case point2:
                target = point3;
                break;
            case point3:
                target = point1;
                break;
        }

        // calculate the dX and dY
        dX = (target[0] - circle.position.x)/steps;
        dY = (target[1] - circle.position.y)/steps;

    }

    // do the movement
    circle.position.x += dX;
    circle.position.y += dY;
}

工作演示

于 2012-09-06T08:22:12.930 回答
4

更多控制速度的解决方案:

  • 移动与时间成正比
  • 可以按像素/秒设置速度

http://jsbin.com/cukine/28/edit?html,输出

var offset = 0;

circle.onFrame = function (event) {
  if (offset< path.length){
    circle.position =path.getPointAt(offset);
    offset+=event.delta*150; // speed - 150px/second
  }
  else {
    offset=0;
  }
}
于 2014-06-06T14:29:08.977 回答
2

这是简单的解决方案,我添加了一个名为 Point 的方法,getPointAtPercent因此现在您可以在路径上运行该方法以获取该点的位置。

paper.Path.prototype.getPointAtPercent = function (percent) {
    return this.getLocationAt(percent * this.length).getPoint();
};

这是它工作的一个例子

http://jsfiddle.net/icodeforlove/uqhr8txp/1/

于 2015-12-06T17:09:04.727 回答
0

您必须使用:

path.getLocationAt();

方法。此方法接受一个介于 0 和 1 之间的参数,其中 0 表示路径的起点,1 表示路径的终点并返回一个位置。

您可以使用:

path.length

属性来计算参数的不同偏移量

steps = lengthOfSegmentToWalk / path.length
t = 0;
while( t <= 1  ){
    location = path.getLocationAt( t );
    t += step;
}

祝你好运

编辑::

或者你可以使用

path.flatten( maxDistance );

方法并从结果路径中读取所有点...

于 2012-09-06T07:52:43.060 回答