使用PaperJs为线条绘制动画

时间:2013-09-10 13:39:57

标签: javascript html5-canvas paperjs

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<!-- Load the Paper.js library -->
<script type="text/javascript" src="paper.js"></script>
<!-- Define inlined PaperScript associate it with myCanvas -->
<script type="text/paperscript" canvas="myCanvas">

    // Create a Paper.js Path to draw a line into it:
    var path = new Path();
    // Give the stroke a color
    path.strokeColor = 'black';
    var start = new Point(100, 100);
    // Move to start and draw a line from there
    path.moveTo(start);
    // Note the plus operator on Point objects.
    // PaperScript does that for us, and much more!
    function onFrame(event) {
        // Your animation code goes in here
        for (var i = 0; i < 100; i++) {
            path.add(new Point(i, i));
        }
    }

</script>
</head>
<body style="margin: 0;">
    <canvas id="myCanvas"></canvas>
</body>
</html>

加载页面时,会绘制一条线。但是我试图动画从A点到B点的线条的绘制。我上面的尝试似乎没有做任何事情......它只是在页面加载时绘制线条而没有从A到B的实际线条的动画

参考。 http://paperjs.org/download/

1 个答案:

答案 0 :(得分:4)

由于您在每个帧上运行for循环,因此您将一次又一次地重复创建相同的线段。相反,您需要每帧添加一个段:

// Create a Paper.js Path to draw a line into it:
var path = new Path();
// Give the stroke a color
path.strokeColor = 'black';
var start = new Point(100, 100);
// Move to start and draw a line from there
// path.moveTo(start);
// Note the plus operator on Point objects.
// PaperScript does that for us, and much more!
function onFrame(event) {
    // Your animation code goes in here
    if (event.count < 101) {
        path.add(start);
        start += new Point(1, 1);
    }
}

if语句用作行长度的限制。

另请注意,如果您的路径还没有任何段,则path.moveTo(start)命令没有任何意义。

如果您不想每帧添加点,但只想更改线的长度,只需更改其中一个线段的位置即可。首先创建向路径添加两个段,然后更改第二个段的每帧事件点的位置:

// Create a Paper.js Path to draw a line into it:
var path = new Path();
// Give the stroke a color
path.strokeColor = 'black';
path.add(new Point(100, 100));
path.add(new Point(100, 100));
// Move to start and draw a line from there
// path.moveTo(start);
// Note the plus operator on Point objects.
// PaperScript does that for us, and much more!
function onFrame(event) {
    // Your animation code goes in here
    if (event.count < 101) {
        path.segments[1].point += new Point(1, 1);
    }
}