Использование 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>

При загрузке страницы рисуется линия. Но я пытаюсь анимировать рисование линии от точки А до Б. Моя попытка выше, похоже, ничего не делает... она просто рисует линию при загрузке страницы без анимации фактической линии, идущей от А до Б. .

Ссылка http://paperjs.org/download/


person user1477388    schedule 10.09.2013    source источник


Ответы (1)


Поскольку вы запускаете цикл 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);
    }
}
person Alex Blackwood    schedule 10.09.2013
comment
Спасибо за хороший ответ. Мне интересно: это создает 100 точек для рисования линии... Есть ли способ нарисовать анимированную линию всего двумя точками (A и B)? - person user1477388; 10.09.2013