PaperJS - 如何沿路径移动并沿路径旋转
PaperJS - How to move along path and rotate along the path
here中显示的示例展示了如何在 Paperjs 中沿路径移动对象,但如何沿路径正确旋转对象?
在上面link的例子中,大家建议以圆圈为例。但是一旦变成了一个矩形new Path.Rectangle(new Point(20,20), new Size(20,20));
你可以看到它沿着路径移动但实际上并没有沿着路径的方向旋转
如何计算旋转并将其设置到我的对象?
为了计算旋转,您需要知道矩形位置路径的切向量。
这可以用 path.getTangentAt(offset) 方法检索。
然后,为项目旋转设置动画的简单方法是将 item.applyMatrix
设置为 false
,然后在每一帧上为 item.rotation
属性 设置动画。
这里是 sketch 演示解决方案。
// Create the rectangle to animate along the path.
// Note that matrix is not applied, this will allow us to easily animate its
// rotation.
var rectangle = new Path.Rectangle({
point: view.center,
size: new Size(100, 200),
strokeColor: 'orange',
applyMatrix: false
});
// Create the path along which the rectangle will be animated.
var path = new Path.Circle({
center: view.center,
radius: 250,
strokeColor: 'blue'
});
// On each frame...
function onFrame(event) {
// ...calculate the time of the animation between 0 and 1...
var slowness = 400;
var time = event.count % slowness / slowness;
// ...and move the rectangle.
updateRectangle(time);
}
function updateRectangle(time) {
// Calculate the offset relatively to the path length.
var offset = time * path.length;
// Get point to position the rectangle.
var point = path.getPointAt(offset);
// Get tangent vector at this point.
var tangent = path.getTangentAt(offset);
// Move rectangle.
rectangle.position = point;
// Rotate rectangle.
rectangle.rotation = tangent.angle;
}
here中显示的示例展示了如何在 Paperjs 中沿路径移动对象,但如何沿路径正确旋转对象?
在上面link的例子中,大家建议以圆圈为例。但是一旦变成了一个矩形new Path.Rectangle(new Point(20,20), new Size(20,20));
你可以看到它沿着路径移动但实际上并没有沿着路径的方向旋转
如何计算旋转并将其设置到我的对象?
为了计算旋转,您需要知道矩形位置路径的切向量。
这可以用 path.getTangentAt(offset) 方法检索。
然后,为项目旋转设置动画的简单方法是将 item.applyMatrix
设置为 false
,然后在每一帧上为 item.rotation
属性 设置动画。
这里是 sketch 演示解决方案。
// Create the rectangle to animate along the path.
// Note that matrix is not applied, this will allow us to easily animate its
// rotation.
var rectangle = new Path.Rectangle({
point: view.center,
size: new Size(100, 200),
strokeColor: 'orange',
applyMatrix: false
});
// Create the path along which the rectangle will be animated.
var path = new Path.Circle({
center: view.center,
radius: 250,
strokeColor: 'blue'
});
// On each frame...
function onFrame(event) {
// ...calculate the time of the animation between 0 and 1...
var slowness = 400;
var time = event.count % slowness / slowness;
// ...and move the rectangle.
updateRectangle(time);
}
function updateRectangle(time) {
// Calculate the offset relatively to the path length.
var offset = time * path.length;
// Get point to position the rectangle.
var point = path.getPointAt(offset);
// Get tangent vector at this point.
var tangent = path.getTangentAt(offset);
// Move rectangle.
rectangle.position = point;
// Rotate rectangle.
rectangle.rotation = tangent.angle;
}