Two.js is an API that makes it easy to create 2D shapes with code. Follow along and you'll learn how to create and animate shapes from JavaScript.
Two.js is renderer agnostic, so you can rely on the same API to draw 2D with Canvas, SVG, or WebGL. The library has a lot of methods which can be used to control how different shapes appear on the screen or how they are animated.
The uncompressed version of the library has a size of around 128 KB, while the compressed version is 50 KB. If you are using the latest version, you can further reduce the size of the library using a custom build.
You can either download the minified version of the library from GitHub or you can link directly to the CDN hosted version. Once you have added the library to your webpage, you can start drawing and animating different shapes or objects.
First, you need to tell Two.js about the element on which you want to draw 2D and animate your shapes. You can pass some parameters to the two.makeLine(x1, y1, x2, y2). Here, two.makeRectangle(x, y, width, height) and two.makeCircle(x, y, radius) and two.makeArrow(x1, y1, x2, y2, size) method. The y1 values determine the position of the tail of the arrow. The y2 values determine the position of the arrowhead. The fifth parameter determines the size of the arrowhead.
There is a method called radius determines the distance of the polygon's vertices from the center, while two.makeGroup(objects). You can either pass a list of different objects or pass an array of objects, paths or groups as the parameter to this method. It will also return a fill, linewidth values at once.
var rects = [];<br><br>var elemWidth = document.querySelector("#draw-shapes").offsetWidth;<br><br>for (i = 0; i < 100; i++) {<br> rects[i] = two.makeRectangle(<br> Math.floor(Math.random() * elemWidth * 2),<br> Math.floor(Math.random() * 420 * 2),<br> 10 + Math.floor(Math.random() * 100),<br> 10 + Math.floor(Math.random() * 100)<br> );<br>}<br><br>var group = two.makeGroup(...rects);<br><br>group.noFill();<br>group.stroke = "black";<br>group.linewidth = 6;<br><br>two.update();<br>
You can click anywhere inside the div to change the position of the rectangles. We will actually be setting the position of the group. Since the rectangles are part of the group, they will move automatically.
For practice, you should try to modify the code and split the rectangles into two equal groups. Apply a different set of stroke color values to each of them to create your own unique geometric art piece.
You can define both linear and radial gradients in Two.js. Defining a gradient does not mean that it will be rendered automatically on the screen, but it will be available for you to use when setting the two.makeLinearGradient(x1, y1, x2, y2, stops). The values new Two.Stop(offset, color, opacity), where two.makeRadialGradient(x, y, radius, stops, fx, fy). In this case, the values two.makeText(message, x, y, styles). It might be evident from the name of the parameters that message<code >message
is the actual text that you want to write. The parameters x<code >x
and y<code >y
are the coordinates of the point which will act as the center for writing the text. The styles<code >styles
parameter is an object which can be used to set the values of a large set of properties.
You can use styles to set the values of properties like font family<code >family
, size<code >size
, and alignment<code >alignment
. You can also specify the value of properties like fill<code >fill
, stroke<code >stroke
, opacity<code >opacity
, rotation<code >rotation
, scale<code >scale
, and translation<code >translation
.
After learning about all these methods and properties, it is time to apply them to a project. In this tutorial, I will show you how we can use Two.js to render the first ten elements of the periodic table with electrons rotating around the nucleus. The nucleus will also have some slight movement to improve the visual appeal of our representation.
We begin by defining some variables and functions which will be used later.
var rects = [];<br><br>var elemWidth = document.querySelector("#draw-shapes").offsetWidth;<br><br>for (i = 0; i < 100; i++) {<br> rects[i] = two.makeRectangle(<br> Math.floor(Math.random() * elemWidth * 2),<br> Math.floor(Math.random() * 420 * 2),<br> 10 + Math.floor(Math.random() * 100),<br> 10 + Math.floor(Math.random() * 100)<br> );<br>}<br><br>var group = two.makeGroup(...rects);<br><br>group.noFill();<br>group.stroke = "black";<br>group.linewidth = 6;<br><br>two.update();<br>
The above code stores the coordinates of the center of our window in the variables centerX<code >centerX
and centerY<code >centerY
. These will be used later to place our atom in the center. The elementNames<code >elementNames
array contains the names of the first ten elements of the periodic table. The index of each name corresponds to the number of electrons and protons of that element, and it begins with an empty string. The styles<code >styles
object contains properties for styling the text object.
We have also defined a function intRange()<code >intRange()
to get a random integer value within given extremes.
var centerX = window.innerWidth / 2;<br>var centerY = window.innerHeight / 2;<br><br>var elem = document.getElementById("atoms");<br><br>var elementNames = [<br> "",<br> "Hydrogen",<br> "Helium",<br> "Lithium",<br> "Beryllium",<br> "Boron",<br> "Carbon",<br> "Nitrogen",<br> "Oxygen",<br> "Fluorine",<br> "Neon"<br>];<br><br>var styles = {<br> alignment: "center",<br> size: 36,<br> family: "Lato"<br>};<br><br>var nucleusCount = 10;<br>var nucleusArray = Array();<br><br>var electronCount = 10;<br>var electronArray = Array();<br><br>function intRange(min, max) {<br> return Math.random() * (max - min) + min;<br>}<br>
This creates an instance of Two and defines two radial gradients. The red/black radial gradients will represent protons, and blue/black gradients will represent neutrons.
We have used the intRange()<code >intRange()
function to place all these neutrons and protons within 20 pixels of each other. The makeCircle()<code >makeCircle()
method also sets the radius of these protons and neutrons to 10 pixels. After that, we iterate over nucleusArray<code >nucleusArray
and fill each circle with a different gradient alternately.
var rects = [];<br><br>var elemWidth = document.querySelector("#draw-shapes").offsetWidth;<br><br>for (i = 0; i < 100; i++) {<br> rects[i] = two.makeRectangle(<br> Math.floor(Math.random() * elemWidth * 2),<br> Math.floor(Math.random() * 420 * 2),<br> 10 + Math.floor(Math.random() * 100),<br> 10 + Math.floor(Math.random() * 100)<br> );<br>}<br><br>var group = two.makeGroup(...rects);<br><br>group.noFill();<br>group.stroke = "black";<br>group.linewidth = 6;<br><br>two.update();<br>
Placing neutrons and protons inside the nucleus was easy. However, properly placing the electrons at a uniform distance will require a little maths. We use the shellRadius
variable to specify the distance of different electron shells from the nucleus. A whole circle covers an angle equal to 2 PI radians. We can place different electrons uniformly by distributing the 2 PI radians between them equally.
The Math.cos()
and Math.sin()
functions are used to separate the vertical and horizontal components of the position vector of different electrons based on their angle.
var centerX = window.innerWidth / 2;<br>var centerY = window.innerHeight / 2;<br><br>var elem = document.getElementById("atoms");<br><br>var elementNames = [<br> "",<br> "Hydrogen",<br> "Helium",<br> "Lithium",<br> "Beryllium",<br> "Boron",<br> "Carbon",<br> "Nitrogen",<br> "Oxygen",<br> "Fluorine",<br> "Neon"<br>];<br><br>var styles = {<br> alignment: "center",<br> size: 36,<br> family: "Lato"<br>};<br><br>var nucleusCount = 10;<br>var nucleusArray = Array();<br><br>var electronCount = 10;<br>var electronArray = Array();<br><br>function intRange(min, max) {<br> return Math.random() * (max - min) + min;<br>}<br>
This part of the code puts electrons from different shells as well as neutrons and protons in their own separate groups. It also sets the fill colors for all electrons in a specific orbit at once.
var two = new Two({ fullscreen: true }).appendTo(elem);<br><br>var protonColor = two.makeRadialGradient(<br> 0,<br> 0,<br> 15,<br> new Two.Stop(0, "red", 1),<br> new Two.Stop(1, "black", 1)<br>);<br><br>var neutronColor = two.makeRadialGradient(<br> 0,<br> 0,<br> 15,<br> new Two.Stop(0, "blue", 1),<br> new Two.Stop(1, "black", 1)<br>);<br><br>for (i = 0; i < nucleusCount; i++) {<br> nucleusArray.push(two.makeCircle(intRange(-10, 10), intRange(-10, 10), 8));<br>}<br><br>nucleusArray.forEach(function(nucleus, index) {<br> if (index % 2 == 0) {<br> nucleus.fill = protonColor;<br> }<br> if (index % 2 == 1) {<br> nucleus.fill = neutronColor;<br> }<br> nucleus.noStroke();<br>});<br>
This part of the code sets the opacity of individual electrons and protons to zero. It also tells Two.js to rotate the electrons and protons at specific speeds.
for (var i = 0; i < 10; i++) {<br> if (i < 2) {<br> var shellRadius = 50;<br> var angle = i * Math.PI;<br> electronArray.push(<br> two.makeCircle(<br> Math.cos(angle) * shellRadius,<br> Math.sin(angle) * shellRadius,<br> 5<br> )<br> );<br> }<br> if (i >= 2 && i < 10) {<br> var shellRadius = 80;<br> var angle = (i - 2) * Math.PI / 4;<br> electronArray.push(<br> two.makeCircle(<br> Math.cos(angle) * shellRadius,<br> Math.sin(angle) * shellRadius,<br> 5<br> )<br> );<br> }<br>}<br>
The final part of the code allows us to iterate through the elements by clicking the mouse or tapping. To load the next element, we make one more electron and one more proton or neutron visible and update the element name. After clicking on the last element, all the particles are hidden again so we can start over. The visible
variable keeps track of the number of atomic particles that are currently visible so that we can show or hide them accordingly.
Try clicking or tapping in the following CodePen demo to see the first ten elements of the periodic table.
We began this tutorial with a brief introduction to the Two.js library and how it can be used to draw shapes like rectangles, circles, and ellipses. After that, we discussed how we can group different objects to manipulate them all at once. We used this ability to group elements to translate and rotate them in synchronization. These tools all came together in our animation of the atoms of the first ten elements in the periodic table.
As you can see, creating animated 2D graphics is very easy using Two.js. The focus of this post was to help you get started quickly, so we only covered the basics. However, you should read the official documentation to learn more about the library!
The above is the detailed content of A Beginner's Guide to Drawing 2D Graphics With Two.js. For more information, please follow other related articles on the PHP Chinese website!