Getting Started With Paper.js: Projects and Items

You may or may not have heard of Paper.js. So, let's begin with the question: what is Paper.js? It is a library that allows you to create and work with vector graphics. The official website describes it as the Swiss Army Knife of Vector Graphics Scripting. 

Despite the fact that the library has a lot to offer, it is easy to learn even if you have never heard of it before. In this tutorial I will begin with the very basics of the library and then move on to complex topics later.

Using PaperScript

There are two ways to use the library. You can use PaperScript, which is an extension of JavaScript, and help get things done a bit more quickly, or you can just use plain old JavaScript.

PaperScript is just the same old JavaScript that you have always been using. However, it adds support for mathematical operators for point and size objects. It also simplifies the installation of event handlers for Project, View, and mouse Tool objects. 

When loading PaperScript, you have to use the usual script tag with type set to "text/paperscript". If you are loading the code externally, you also need to add a <script> tag with the appropriate URL to load your code. One last attribute that you need to specify is data-paper-canvas="canvasId", or the shorthand version canvas="canvasId", which tells the library about the canvas that it needs to work on. The code below creates a quadrilateral in PaperScript.

Using JavaScript

If you are not comfortable with PaperScript, you can also use JavaScript in your projects. You will have to add a few more lines of code if you decide to do it this way. The first thing that you need to do is check if the DOM is ready because you won't be able to work with the canvas before that. After that you can set up a project and a view using the paper object. All the Paper.js classes and objects will now be accessible only through the paper object. 

As I pointed out earlier, you will have to use Math functions instead of operators when working with Point and Size. The code below illustrates all these differences:

As evident from the code snippets above, it is relatively easy to use PaperScript when working with Paper.js. Therefore, all the examples from now on will be based on PaperScript.

Project Hierarchy

If you have ever used a graphic design application like Adobe Photoshop or Illustrator, you must be familiar with the concept of layers. Each layer in these programs has its own content which, when combined with other layers, creates the final result. Similar layers also exist in Paper.js and can be accessed using project.layers

Initially, every project has a single layer which is accessible through project.activeLayer. Any new items that you create are added to the currently active layer as its child. All the children in a specific layer can be accessed using the layer.children property of the active layer.

There are multiple ways to access all these children. If you only need access to the first and last child of any item, you can use item.firstChild and item.lastChild respectively. You can also assign a specific name to any child and then use that name to access it later. Let's say a layer you are working on has about 30 children. It is not practical to go over all of them one by one. For this reason, the library has a layer.children.length property which you can use to get the total number of children and then iterate over the list using a for loop. 

This code snippet accesses various children using all the properties we just discussed:

The embedded demo below shows the script in action. You can verify that the color of all circles matches the color that we assigned to them in the code above.

You can also use the item.parent method to access the parent of an item, like the item.children method, which you used to access all its children. Whenever you create a new item, its parent will always be the currently active layer of the project. However, it can be changed by adding the item as a child of another layer or group

Before going any further, let me explain what a group actually is. To be honest, both layer and group are very similar. One major difference between these two is that any new items that you create are automatically added to the active layer, but in the case of a group, you will have to add the items yourself. 

There are multiple ways in which you can add items to a group. You can pass an item of arrays to the group constructor and they will all be added to the group's item.children array. To add elements to a group once it has been created, you can use the item.addChild(item) function. You can also insert a child at a specific index using the item.insertChild(index, item) function. 

Removing items is also just as easy as adding them. To remove any item from a project, you can use the item.remove() function. Keep in mind that this won't destroy the item, and it can be added back to the project any time you want. If the item you removed had any children, all of the children will be removed as well. What if you want to remove all the children but keep the item intact? This can be achieved by using the item.removeChildren() function.

Understanding Items

The term item has appeared more than a few times in the tutorial now. So, what is it? Everything that appears within a Paper.js project is an item. This includes layers, paths, groups, etc. While different items have properties that are specific to them, other properties are applicable to all of them.

If you intend to hide an item from the user, you can do so by setting the value item.visible to false. You can also clone any item using the item.clone() function. This function returns the cloned item, which you can store in a variable and manipulate later. You can also change the opacity of any item using the item.opacity property. Any value between 0 and 1 will make the item translucent.

You can also set a blend mode for any item using the item.blendMode property. The blend mode needs to be passed as a string. The library also provides an item.selected property which, if set to true, creates a visual outline on top of that element. This can be pretty useful during debugging as it allows you to see the construction of paths, individual segment points, and bounding boxes of items.

Item Transformations

Items can be scaled, rotated or moved around in a Paper.js project with ease. In this section, I will cover all these transformations briefly. 

To change the position of an item, you can use its item.position property and set the position to a new point. If you want to move an element around, you can do so with the help of the += operator.

You can also scale any item by using the item.scale(scale) function. This will scale the item around its center point. You can scale an item around some other point by specifying it as a second parameter, like item.scale(scale, point). Moreover, the library also allows you to scale items differently in vertical and horizontal directions by passing two numbers as parameters, like item.scale(scaleX, scaleY).

Rotating items is similar to scaling them. You can use the item.rotate(angle) function to rotate elements around their center. The angle is specified in degrees, and rotation occurs in a clockwise direction. To rotate an item around a specific point, you can also pass a point as a second parameter, like item.rotate(angle, point)

The following code snippet applies all the transformations and manipulations that we just discussed on three different rectangles.

The code is pretty much self-explanatory. I clone rectangle B from rectangle A, and rectangle B acquires all properties of rectangle A. The same goes for rectangle B and C. 

Note that I have used the += operator that I discussed above to move the items around. This operator moves items relative their old positions instead of using absolute values.

The demo below shows you the final result after all these transformations. You can try out different blend-modes or change other properties in the demo to see how they affect the final result.

Final Thoughts

As I mentioned earlier, Paper.js is easy to learn and allows you to create vector graphics with ease. This tutorial covered the very basics that you need to know to work with the library. Soon, we will publish the next tutorial of the series, which will discuss paths and geometry in detail. 

In the meantime, it's important to note that JavaScript has become one of the de facto languages of working on the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

Until then, I suggest that you create a few basic demos of our own and practise what you have learned so far. If you have any questions regarding this tutorial, let me know in the comments.

Tags:

Comments

Related Articles