One Two.JS
A Guide to Help Your Exploration With Two.JS
Tired of casual styling or animation for your web? Step up your work right here, right now.
In this article, we’ll make some cool things using Javascript with the help of Two.js.
Two.js is a two-dimensional drawing api geared towards modern web browsers. It is renderer agnostic enabling the same api to draw in multiple contexts: svg, canvas, and webgl.
Below are features Two.js deliver such as :
Focus on Vector Shapes
Two.js is deeply inspired by flat motion graphics. As a result, two.js aims to make the creation and animation of flat shapes easier and more concise.
Scenegraph
At its core two.js relies on a scenegraph. This means that when you draw or create an object (a Two.Path or Two.Group), two actually stores and remembers that. After you make the object you can apply any number of operations to it — e.g: rotation, position, scale, etc..
Animation Loop
Two.js has a built-in animation loop. It is simple in nature and can be automated or paired with another animation library. For more information check out the examples.
SVG Interpreter
Two.js features a Scalable Vector Graphics Interpreter. This means developers and designers alike can create SVG elements in commercial applications like Adobe Illustrator and bring them into your two.js scene. For more information check out the examples.
Friends with Bitmap Imagery
Despite its early focus on easing vector shape creation and animation, Two.js offers many easy-to-use features to handle and render bitmap images. Easily load single images, sprite sheets, and image sequences with just a few method calls.
Or in a nutshell, Two.js is a helpful library that helps us draw, design, and animate two dimensional shapes or objects.
By the end of this tutorial, you’ll be able to create simple shapes and some animations with a little JS knowledge, LFG!!
Let’s get started with Two.js installation. For the sake of simplicity, we’ll just use plain JS to work on.
# Project setup
Create a new folder and feel free to give it a name.
On the root folder, create :
- index.html
- index.js
- two.js
I’ll save the explanation for each file on the next few steps.
Two.js
Open Two.js official site (two.js.org), find the “Download” section.
We’ll choose the Production one. Simply copy all the code and put it on the file named “two.js”.
Here the “two.js “ file contains all the Two.js code that we’ve copied before. What we want to do next is import the “two.js” file to our project so we can use all Two.js features.
index.html and index.js
In this section we’ll add changes to both “index.html” and “index.js” which enables us to use Two.js on our project.
<!-- index.html --><head> <script src="./two.js"></script></head><body> <script src="./index.js"></script></body>
The <head> tag is a container for metadata about the HTML document. (Metadata is not displayed)
<head> <script src=”./two.js”></script></head>
We use the ``script`` tag on an HTML file to import script from a javascript file. In our case, ``script`` tag is used in index.html to import “two.js”.
<body> <script src=”./index.js”></script></body>
Meanwhile, the reason why we use the ``script`` tag on the ``body`` section is because we want to create our animation and put it into the HTML <body>.
// index.jsconst elem = document.bodyconst two = new Two({ fullscreen: true}).appendTo(elem)const circle = two.makeCircle(70, 0, 50)circle.fill = '#FF8000'circle.linewidth = 10const rect = two.makeRectangle(-70, 0, 100, 100)rect.fill = 'rgba(0, 200, 255, 0.75)'rect.noStroke()var group = two.makeGroup(circle, rect)group.position.set(two.width / 2, two.height / 2)group.stroke = '#63A355'group.scale = 0.7two.update()
Before we do the draws, start by declaring a new Two.js canvas then append it to our HTML body.
const elem = document.bodyconst two = new Two({ fullscreen: true}).appendTo(elem)
# Make Two.js Shapes
Now, the SHAPES part. Below are some shapes that we can create using Two.js.
We’ll create 2 simple shapes; circle and rectangle. Let’s take a look at the “makeBlabla” function. These are the functions that Two.js provide us to make shapes.
Two.makeCircle()
The makeCircle function receives 4 parameters which are X coordinate position (x), Y coordinate position (y), circle’s diameter (radius), amount of anchor on circle path (resolution).
const circle = two.makeCircle(70, 0, 50)
The expected result of this line of code is we created a circle with coordinates of (70, 0), radius of 50. Since we didn’t provide a resolution parameter on the makeCircle function, they’ll set it to default value of 4.
Two.makeRectangle()
Two.makeRectangle() have 4 parameters, X coordinates (x), Y coordinates (y), width of the rectangle (width), and height of the rectangle (height).
const rect = two.makeRectangle(-70, 0, 100, 100)
Code above will create a rectangle shape that starts at (-70, 0) coordinates with width of 100 and height of 100.
circle.fill = ‘#FF8000’circle.linewidth = 10
Plus you can set the properties of the object such as fill, stroke, linewidth, etc. For a complete guide about shapes properties you can refer to Two.js documentation.
# Grouping Shapes
Let’s say that we want to align the shapes together in the center of the canvas, put some animation, or configure shapes styles. We can achieve those by grouping the shapes. Groups can take an array of shapes and/or groups.
const group = two.makeGroup(circle, rect);
Here we try to make a group containing a circle and rectangle. Two.makeGroup() receives parameters containing the shapes that we want to add to the group.
group.position.set(two.width / 2, two.height / 2)group.stroke = '#63A355'group.scale = 0.7
Just like shapes, you can configure some properties tooooooo, ez pz.
# Render Your Canvas
After creating all the shapes, arrange it to group, configure some shapes properties, you want to render your canvas so all the shapes can appear on the HTML page. Simply call this line of code
two.update()
TA-DA!!!
Result :
# Applying Animation
Now here are the cool things. After adjusting all the shapes, bringing it into canvas, we can finally apply some animation into our shapes or groups.
elem.addEventListener('click', play, false)two.bind('update', update)function play() { if(two.playing) { two.pause() }else { two.play() }}function update() { if (group.rotation >= Math.PI * 2) { group.rotation = 0; } group.rotation += Math.PI/30;}
Result :
Here we’ve implemented some animation with an event listener. So everytime we do ‘click’ on the ‘elem’ (document.body) section, ‘elem’ will invoke the ‘play’ function.
elem.addEventListener('click', play, false)
Dooooon’t forget that we also need to bind an event listener to our canvas
two.bind('update', update)
Bind function allows you to call a listener to a specific event name. This function accepts two parameters, event name and handler. Event name stands for the specific event that we want the canvas to listen to. The second parameter, handler, is the callback function whenever the event is triggered.
function play() { if(two.playing) { two.pause() }else { two.play() }}
On the canvas keyframes, there are three properties that we can use. Two.playing returns a boolean which is true if canvas keyframes are playing. Two.pause() is a function to pause canvas keyframes from playing. Meanwhile Two.play() is the opposite of Two.pause().
function update() { if (group.rotation >= Math.PI * 2) { group.rotation = 0; } group.rotation += Math.PI/30;}
Update function is the function that we used as the callback function on the two.bind() function. The function contains the animation properties, we first check if the object rotation exceeds the PI rotation is true, then we set the rotation back to 0. Then we also increment the object rotation by PI / 30. You’ll be asking where the ‘PI / 30’ comes from, AM I RIGHT???. Simple explanation, a whole 360 degree rotation is PI * 2. Each second contains 60 frames. So we can get the formula to get incremental value for each frame which is PI * 2 / 60 or PI /30.
# Conclusion
Aaandd here we are at the end of Two.js tutorial. To sum up, Two.js is a simple yet powerful library. It allows you to bring all your creative things together and make those work easily. Packed with a lot of functions and features, Two.js is really fun and worth exploring if you’re up for drawing or animating things. The guide above is a little step to help you guys get more familiar with the mechanism of Two.js. Alright, let’s do some cool stuff on the next guide, shall we?
PEACE OUT.