Quick-start

A clear step-by-step demonstration of Pencil.js

Come along, to create a nice animation in 50 lines of code.
You can easily follow, as each of the 9 steps introduces one feature at a time.
This is the easiest way to get to know Pencil.js and should take about 5 minutes to read.

Setup

On capable browsers, you can use the import statement to load Pencil.js.

First thing you will need is a {Scene}. Once created, you can render it to display its content.

Next, we will start to add a {Component} and see the real power of the library.

Components

Everything drawn in Pencil.js is a {Component}. They all share the same behavior.

You will always declare {Component} with a position followed by one or more parameters. For example, {Circle} only needs a position and a radius.

Once a {Component} is added to a {Scene} or another {Component}, it will be displayed on screen.

Options

In order to control the look of our {Circle}, let's change its options and rename it to sun to match its new look.

Let's also change the {Scene}'s background color. Because we don't want to change the first argument of the {Scene} constructor, we can leave it at undefined.

In the same way, we can add the ocean with a {Rectangle}.

Interaction

A lot of Pencil.js is build around interaction with the user so you can build beautiful and interesting composition.

Firstly, we need to replace the render function (which render the scene only once) to startLoop. This will make the scene update itself.

Secondly, let's make the sun follow the mouse. For that, we'll listen to the "draw" event and update the sun's position.

The lerp function moves the position by 5% of the distance each time, giving it a smoother animation.

Colors

The sun is setting, but the sky color stay the same. We can improve this by changing the sky's color according to the sun's position.

Note that, like {Position}, {Color} also have a lerp function to go from one color to another.

Now, let's do the same for the ocean. But instead of changing the color, let's add a gradient and move it around.

Particles

Final touch! Let's add stars when the sky turn dark. We could add a bunch of {Star}s, but this could have an impact on drawing performance. Instead, let's use {Particles}. They perform better when you want to draw the same shape thousands of times.

And voila!

Now it's your turn to build amazing things and share them with us!

For a more in depth presentation of Pencil.js, take a look at the official guide.