An Easy Image Carousel

By Vaibhav Choudhary, October 22, 2008

With the JavaFX technology it is easy to build your own customized carousel with a simple graphics operation and binding.

Understanding the Code

The code shown in Figure 1 creates a carousel. Most of the drawing is based on public attributes, enabling you to easily customize the look by changing a few settings.

Source Code

package carousel;

import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.Node;
import java.lang.Math;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.scene.input.MouseEvent;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.effect.*;
import java.lang.System;

// these variable decide the position at the beginning
var y=0;
var speed=5;
var radius=100;
var xcenter=70;
var ycenter=50;
var zcenter=100;
var radius_y = 50;

var fl=100;      // used for scaling factor. Basically it will work like a camera at Z axis.
var shift = Math.PI/2;
var image_gap = Math.PI/3;  // placement of each image at PI/6 distance,because of 6 images.
var angle;
var angle_rad=angle*Math.PI/180;public class Carousel extends CustomNode {

    public var X: Number;
    public var Y: Number;
    public var Z: Number;
    public var image: Image;
    public var scale: Number;

    public override function create(): Node {
        System.out.println(image);
        return Group {
            content: [
                ImageView {
                x: bind X
                y: bind Y
                scaleX: bind scale
                scaleY: bind scale
                opacity: bind scale
                image: bind image
                }
            ]

        };
    }

    public function update(i:Number,angle: Number): Void {
        Z=Math.sin(angle + i*image_gap + shift) * radius + zcenter ;
        scale = fl / (fl + Z);
        X= Math.cos(angle + i*image_gap + shift) * radius + xcenter;
        Y= -Math.sin(angle + i*image_gap + shift) * radius_y + ycenter ;
     }
  }

Figure 1: Carousel.fx Class

Changing the data member like dur in Main.fx, enables you to make the animation slower or faster.

Source Code
var dur: Duration = 15ms;   // can control speed of rotation on by changing this variable.

Figure 2: Changing the Animation

Customizing the Code

To further customize the carousel, you can use your own image of 100 X 100 pixels by changing the image String array.

Source Code
var im:String[] = ["{__DIR__}im1.PNG", "{__DIR__}im2.PNG","{__DIR__}im3.PNG",
    "{__DIR__}im4.PNG","{__DIR__}im5.PNG","{__DIR__}im6.PNG"];

Figure 3 shows the changed attributes in Main.fx of Carousel.


Figure 3: Carousel with Different Images