Using PaperJs to Animate the Drawing of a Line

2019-09-01 23:07发布

This is my code:

<!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>

When the page is loaded, a line is drawn. But I am trying to animate the drawing of the line from point A to B. My attempt above doesn't seem to do anything... it just draws the line on page load with no animation of the actual line going from A to B.

Ref. http://paperjs.org/download/

1条回答
可以哭但决不认输i
2楼-- · 2019-09-02 00:02

Since you are running the for-loop on every frame, you're re-creating the same line segments over and over, all at once. Instead, you need to add one segment per frame:

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

The if statement serves as a limit for the line's length.

Also note that the path.moveTo(start) command does not mean anything if your path does not yet have any segments.

If you don't want to add points every frame, but only change the length of a line, simply change the position of one of the segments. First create add two segments to your path, then change the position of the second segment's point per frame event:

// 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);
    }
}
查看更多
登录 后发表回答