Sunday, April 05, 2009

JavaFX Path Animation (A Request)

Here is a screen shot from a JavaFX program that performs path animation (a request from a reader).
I just received a request based on a recent JavaFX Path Animation post: How to create an animation that
Path is simple circle.
Object is a line bar.
This bar should move around the circle.
I don't usually do this, but the request was indeed simple and it took a mere 10 minutes to put together the code. (The complete code for the Chutes and Ladders animation is included in the upcoming book I'm writing with Paul Anderson. If you like this, please buy the book. Look for it at--God willling and the stars align--JavaOne.)

Here is the complete code (minus the import statements). For more details on the JavaFX path animation, see the JavaFX 1.1 API.

// change these to change the
// dimensions of the path elements
def startX = 100;
def startY = 100;
def radiusX = 50;
def radiusY = 50;
// this provides the path elements for the animation
// (using PathTransition)
// and the Path (which is a Shape)
def circleElements = [
MoveTo {
x: startX
y: startY + radiusY
ArcTo {
x: startX
y: startY - radiusY
radiusX: radiusX
radiusY: radiusY
ArcTo {
x: startX
y: startY + radiusY
radiusX: radiusX
radiusY: radiusY
// this is the path, not needed for the animation,
// just shows the path
def path = Path {
stroke: Color.DARKGRAY
strokeWidth: 2
elements: circleElements
// marks the center of the "circlePath",
// not needed, just for decoration
def circle = Circle {
centerX: startX
centerY: startY
radius: 5
fill: Color.BLUE
// this is the object that gets animated
// along the path
def lineBar = Rectangle {
width: 40
height: 10
stroke: Color.BLACK
fill: Color.YELLOW
// put all of these things in a group
// you can change the location of the group
// with properties translateX and tranlateY
def group = Group {content: [ path circle lineBar ] }
// This provides the animation
// repeatCount can be a number (defaults to 1)
// also autoReverse: true lets the animation repeat
// in reverse, repeatCount must be at least 2
// for this to have an effect
PathTransition {
repeatCount: Timeline.INDEFINITE
duration: 15s
node: lineBar
orientation: OrientationType.ORTHOGONAL_TO_TANGENT
interpolate: Interpolator.LINEAR
path: AnimationPath.createFromPath(Path {
elements: circleElements
}.play(); // start the animation now

Stage {
title: "Simple Path"
width: 250
height: 250
scene: Scene {
content: group

No comments: