沿路径Paper.js滚动

时间:2013-12-10 21:23:12

标签: javascript path scroll paperjs

基本上我想沿路径滚动一个对象。我已经看到几个线程寻找类似的解决方案,不使用paper.js,但我想知道这是否可能与paper.js。或者有人可以给我一个有效的jsfiddle对象跟踪svg曲线因为我无法得到任何工作。我最终希望有一系列div跟随路径。

// 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.strokeColor = "#FFF";
path.closed = true;

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

// 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;
}

这是jsfiddle: http://jsfiddle.net/J9xgY/12/

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以在path.getPointAt(offset)的路径上找到一个点,其中offset以路径长度为单位进行测量。如果可以计算滑块沿其轨迹的位置,可以将其乘以path.length来获得偏移量。

您可以使用HTML滑块或canvas元素执行此操作,如下所示:

// 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.strokeColor = "#FFF";
path.closed = true;

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

// slider
var sliderLine = new Path(new Point(10,30.5), new Point(210, 30.5));
sliderLine.strokeColor = '#FFF';
var sliderKnob = new Path.Circle(new Point(10,30.5), 5);
sliderKnob.fillColor = '#FFF';

var sliderHit = false;

function onMouseDown(event) {
    if (event.item == sliderKnob) sliderHit = true;
}

function onMouseDrag(event) {
    if (sliderHit === true) {
        if (event.point.x > 10 && event.point.x < 210) {
            sliderKnob.position.x = event.point.x;
        }
        else if (event.point.x < 11) {
            sliderKnob.position.x = 10;
        }
        else if (event.point.x > 209) {
            sliderKnob.position.x = 210;
        }

        // Get offset and set circle position
        var percent = ( sliderKnob.position.x - 10 ) / 200;
        circle.position = path.getPointAt(path.length * percent);             
    }

}

function onMouseUp(event) {
    sliderHit = false;
}

jsfiddle:http://jsfiddle.net/J9xgY/13/

沿着直线单击并拖动实心圆圈,沿三角形移动圆圈。