The Easy Paper.js Tutorial

How to build awesome flat animated shapes with Paper.js.

← andyshora.comworth a tweet?+1

What is Paper.js?

Paper.js is a delightful way of animating vector graphics on HTML5 Canvas. Think 60fps animations, all written with an easy-to-use JavaScript library.

As it's pure Canvas + JS, it works across mobile devices too, with great performance, as it syncs updates with the device's GPU repaint cycle with the aim of achieving a silky-smooth 60fps.

Yeah, it's what I used to make a little animated London skyline on my homepage! I thought it was pretty cool, so here's an intoduction to using Paper.js which I hope some of you find useful.

Paper.js — The Swiss Army Knife of Vector Graphics Scripting.

PaperJS Team

How do I get it?

  1. Download Paper.js from the site and reference locally, or reference the CDN version.
  2. Start writing code!

Show me the code already

Ok ok. Let's draw some shapes.

Paper.js shapes, defined inside <script type="text/paperscript" canvas="myCanvas">
// The Path.Circle constructor takes a Point(x, y), and a radius
var myBall = new Path.Circle(new Point(70, 70), 50);
myBall.fillColor = 'tomato';

// The Path.Rectangle constructor can take a Point and a Size object
var point = new Point(20, 150);
var size = new Size(100, 50);
var myRectangle = new Path.Rectangle(point, size);
myRectangle.fillColor = 'powderblue';

// The Path.Line constructor takes 2 points, defining the start and end of the line.
var from = new Point(160, 20);
var to = new Point(200, 80);
var straightLine = new Path.Line(from, to);
straightLine.strokeColor = 'black';

// The Path.Arc constructor takes 3 points, var names describing the obvious.
var from = new Point(170, 120);
var through = new Point(200, 180);
var to = new Point(170, 220);
var curvedPath = new Path.Arc(from, through, to);
curvedPath.strokeColor = 'black';

A circle is a predefined shape in Paper.js, which means it has a nice abstracted interface which you can use to create the path.

Other handy predefined shapes: Circle, Rectangle, RoundRectangle, RegularPolygon, Line, Arc, Star.

I Can Haz Animations?

Yes chap. You certainly can.

To create animations, define the update logic inside a special onFrame handler, which Paper.js calls up to 60 times per second.

Paper.js animation, rotating a rectangle on every frame refresh.
// create the shape
var point = new Point(20, 150);
var size = new Size(100, 50);
var myRectangle = new Path.Rectangle(point, size);
myRectangle.fillColor = 'powderblue';

function onFrame(event) {
  // On each frame update, rotate the square by 3 degrees:
  myRectangle.rotate(3);
}

Advanced Animation Using Event Properties

Need to perform an animation dependent on time, or just against a scale? i.e. a shape shooting back and forth? You can make use of the following properties of the event object, which is always passed to the onFrame handler. - event.count: Number — the number of times the frame event was fired. - event.time: Number — the total amount of time passed since the first frame event in seconds.

Using event.count and Math.sin() to create a smooth looping animation.
var point = new Point(20, 50);
var size = new Size(100, 50);
var myRectangle = new Path.Rectangle(point, size);
myRectangle.fillColor = 'lightBlue';

var myBall = new Path.Circle(new Point(10, 90), 10);
myBall.fillColor = 'black';

function onFrame(event) {
  // Normalise the event.count property to a 0-359 scale
  // then apply some trigonometry so we get some smoothed values
  // just like going round the edge of a circle
  var x = (1 + Math.cos((event.count * 2 % 360)
    * (Math.PI / 180))) * 100 + 10
  var y = (Math.abs(Math.sin((event.count * 2 % 360)
    * (Math.PI / 180)))) * 80;
  myRectangle.position.x = x;
  myBall.position.x = x;
  myBall.position.y = 90 - y;
}

Using Symbols for multiple instances

Using symbols allows you to create multiple instances of an item really quickly. This also saves memory, which is really important.

Symbols can then be manipulated individually on the instance, or all together using the symbol definition.

Using symbols to create multiple instances of a shape
var squarePath = new Path.Rectangle(new Point(20, 20), new Size(20, 20));
squarePath.fillColor = 'aquamarine';
var squareSymbol = new Symbol(squarePath);

// lets place some squares using symbols, and rotate each instance slightly
for (var i = 0; i < 5; i++) {
  var placedSymbol = squareSymbol.place(new Point(20 + (i * 40), 50));
  placedSymbol.rotate(i * 10); // operation on the instance
}

function onFrame(event) {
 // Add 1 degree to the hue
 // of the symbol definition's fillColor:
 squareSymbol.definition.fillColor.hue += 1;
 // rotate
 squareSymbol.definition.rotate(0.2);
}  

That's Shapes, Done.

So, Paper.js is a really easy way to draw vector shapes on canvas, and animate them to your heart's content.

You can access the instances of the shape you've created (or the symbol definition) just like you would with JavaScript variables, meaning you can do stuff on whatever events you desire.

Check out loads of Paper.js examples on the official site, and view and edit the source with a simple switch to source view in the top right.

I won't get into animating complex paths just yet, but hopefully this tutorial has given you enough code to mess around with some shapes like I did recently. As usual, send me a tweet or leave a comment below if you need a hand!

by Andy Shora

I'm a Front End Web Developer based in London. I love to build sites which are clean and have great performance, and I dabble with whatever technologies are most suitable for the job. Send me tweets!