Monday, September 14, 2009

JavaFX Snowflake

EDIT: I took out the samples. The code is old and dated.

This simple project shows off several basic features: arrays, random numbers and unique ways to use JavaFX's built in effects. Nice results from a simple, one page script.
  • Snowflake Project
Code

Download/View the JavaFX Script here: Main.fx

Prerequisites

Familiar with JavaFX. See my Getting Started with JavaFX post for links.

Code Notes

Creating a Flake

The createFlake function is the heart of the application, called when the application is loaded and when the Create button is clicked. It sets up a Polyline created from a series of random integers which create the x and y points along the line. The random numbers are constrained so the line is contained in a certain area.

var x1 = random.nextInt(20);
var y1 = random.nextInt(20);
var x2 = random.nextInt(100);
var y2 = random.nextInt(100);
var x3 = random.nextInt(40) + 60;
var y3 = random.nextInt(40) + 60;
var x4 = random.nextInt(20) + 80;
var y4 = random.nextInt(20) + 80;

Flake Effects

I used two different effects, but in unique ways.

First, to give the flake a slight glowing feel, I use the DropShadow effect. Instead of using Color.BLACK, I use White and set the offsets to zero. This keeps the like crisp (unlike the blur effect) but gives it a nice glow.

effect: DropShadow {
offsetX: 0;
offsetY: 0;
color: Color.WHITE;
radius: 16;
}

Second, on each Polyline I put in a Reflection effect, but keep it at full opacity. This just throws more randomness in the snowflake lines.

effect: Reflection { //Note the settings for the reflection. Doesn't fade away at bottom
fraction: 0.75;
topOffset: 0.0;
topOpacity: 0.6;
bottomOpacity: 1.0;
};

Things to Play With
  • Try the sample yourself and modify how the random numbers are generated.
  • Add a slider to create more or less points on the Polyline.
  • Add more or less lines in the flake's content by changing the values in the for loop. Be sure the rotation amount ends up with a total of 360 so you get a full flake.
  • Try different effects in each group to see how it changes.

No comments: