nature of code in javafx canvas

Nature of Code in JavaFX Canvas

If you are torn between programming and physical simulations that give pleasing visual results, you wouldn’t want to miss reading The Nature of Code by Daniel Shiffman. The book covers programming techniques to create simulations of natural systems. The language used in the book is Processing. Since I always wanted to be unique and different, I picked JavaFX Canvas to recreate the examples in the book.

The Java Canvas API provides a drawing surface to draw shapes, images and texts, as well as pixel-level access to manipulate every single pixel. The API is similar to HTML Canvas, Processing and P5.js, so jumping from one another is not a problem.

In the Processing programming language, the very basic skeleton of your project are the functions setup() and draw(). The setup() function is being run once at the start of the program. This is where we do all the initializations. On the other hand, the draw() function is called after the setup(), and runs continuously.

Given that I used JavaFX instead of Processing, I still wanted my project to have the same structure with Processing. That’s why I created my own framework so that every animation I create should look like this:

 public class Example extends AnimationCanvas {  
   public Example() {  
     setup = () -> {  
       //insert code here  
      draw = () -> {  
        //insert code here  

Every animation should extend the class AnimationCanvas, and should optionally provide implementation for setup and draw. setup and draw are actually of type Runnable.

All in all, I’ve recreated 20 examples, from basic to advanced. Here are some screenshots:

This slideshow requires JavaScript.

You can download the source codes in my Github repository.