Two.js is an API that allows you to easily create 2D shapes using code. Continuing along, you'll learn how to create and animate shapes with JavaScript.
Two.js is renderer-agnostic, so you can rely on the same API to draw 2D using Canvas, SVG, or WebGL. The library has many methods that can be used to control how different shapes appear on the screen or how they are animated.
The uncompressed version of the library is approximately 128 KB in size, while the compressed version is 50 KB. If you are using the latest version, you can use a custom build to further reduce the size of the library.
You can download a minified version of the library from GitHub or link directly to the CDN-hosted version. Once you've added the library to your web page, you can start drawing and animating different shapes or objects.
First, you need to tell Two.js the element you want to draw 2D on and animate the shape. You can set some parameters by passing them to the Two
constructor.
Use the type
attribute to set the renderer type. You can specify a value such as svg
, webgl
, canvas
, etc. type
is set to svg
. The width and height of the drawing space can be specified using the width
and height
parameters. You can also use the fullscreen
parameter to set the drawing space to the entire available screen. When fullscreen
is set to true, the values of width
and height
are ignored.
Finally, you can tell Two.js to automatically start the animation with the help of the boolean autostart
parameter.
After passing all required parameters to the constructor, you can start drawing lines, rectangles, circles and ovals.
You can use two.makeLine(x1, y1, x2, y2)
to draw a line. Here, (x1, y1)
is the coordinate of the first endpoint, and (x2, y2)
is the coordinate of the second endpoint. The function will return a Two.Line
object which can be stored in a variable for further manipulation later.
In a similar manner, you can use two.makeRectangle(x, y, width, height)
and two.makeRoundedRectangle(x, y, width, height, radius)## respectively # Draw ordinary rectangles and rounded rectangles. Keep in mind that
x and
y determine the center of the rectangle, not the coordinates of the top left corner of the rectangle like many other libraries do. The
width and
height parameters will determine the size of the rectangle.
radius The parameter is used to specify the radius value of the fillet.
two.makeCircle(x, y, radius) and
two.makeEllipse(x, y, width, height) respectively to render circles and Oval. Just like a rectangle, the
x and
y parameters specify the center of a circle or ellipse. If it's an oval, setting
width and
height to the same value will render it circular.
two.makeArrow(x1, y1, x2, y2, size) method. The
x1 and
y1 values determine the position of the arrow's tail. The
x2 and
y2 values determine the arrow's position. The fifth parameter determines the size of the arrow.
two.makePolygon(x, y, radius,sides) that you can use to create a regular polygon. The x and y values determine the center of the polygon.
radius determines the distance from the polygon's vertices to the center, while
sides specifies the number of sides of the polygon.
Objects in Action Group
two.makeGroup(objects). You can pass a list of different objects, or an array of objects, paths, or groups as a parameter to this method. It will also return a
Two.Group object. After you create a group, you can use the properties provided by the group to operate on all its subgroups at once.
The
Stroke
and fill
properties can be used to set the stroke and fill colors of all children in the group. They will accept all valid forms that can represent color in CSS. This means you are free to use RGB, HSL or hexadecimal representation. You can also simply use the name of the color, such as orange
, red
, or blue
. Likewise, you can set the values of all other properties, such as linewidth
, opacity
, miter
, and cap
. You can use the noFill()
and noStroke()
methods to remove the fill and stroke of all children in a group.
You can also apply other physical transformations, such as scale
, rotation
, and translation
. These transformations will be applied to individual objects. New objects can be easily added to the group and removed using methods such as add()
and remove()
.
Here is an example of creating about 40 different rectangles in random locations. The rectangles are then grouped so that we can immediately change their fill
, Stroke
, and linewidth
values.
var rects = []; var elemWidth = document.querySelector("#draw-shapes").offsetWidth; for (i = 0; i < 100; i++) { rects[i] = two.makeRectangle( Math.floor(Math.random() * elemWidth * 2), Math.floor(Math.random() * 420 * 2), 10 + Math.floor(Math.random() * 100), 10 + Math.floor(Math.random() * 100) ); } var group = two.makeGroup(...rects); group.noFill(); group.stroke = "black"; group.linewidth = 6; two.update();
You can click anywhere inside the div to change the position of the rectangle. We're actually going to set the position of this group. Since the rectangles are part of the group, they move automatically.
For practice, you should try modifying the code and dividing the rectangle into two equal groups. Apply different linewidth
and lines
color values to each to create your own unique geometric artwork.
You can define linear and radial gradients in Two.js. Defining a gradient does not mean that it will automatically render on the screen, but it can be used when setting the fill
or Stroke
values of various objects.
You can use two.makeLinearGradient(x1, y1, x2, y2,stops)
to define a linear gradient. The values x1
and y1
determine the coordinates at which the gradient begins. Likewise, the values x2
and y2
determine the coordinates at which the gradient ends. The stops
parameter is an array of Two.Stop
instances. They define the color of each part of the array and where each color transitions to the next. They can be defined using new Two.Stop(offset, color, opacity)
, where offset
determines the point on the gradient at which that specific color must be fully rendered. color
Parameter determines the color of the gradient at specific points. You can use any valid CSS color representation as its value. Finally, the opacity
parameter determines the opacity of the color. Opacity is optional and can be any value between 0 and 1.
You can define a radial gradient in a similar way using two.makeRadialGradient(x, y, radius,stops, fx, fy)
. In this case, the values x
and y
determine the center of the gradient. The radius
parameter specifies how far the gradient should extend. You can also pass an array of stop points to this method to set the color composition of the gradient. The parameters fx
and fy
are optional and can be used to specify the focus position of the gradient.
Check out some gradient types and their code in the CodePen below.
Remember that the x
and y
gradients are positioned relative to the origin of the shape they are trying to fill. For example, a radial gradient that should fill a shape from the center will always set x
and y
to zero.
Two.js also allows you to write text on the drawing area and update it later to suit your needs. This requires using the method two.makeText(message, x, y, styles)
. It's obvious from the parameter names that message
is the actual text you want to write. The parameters x
and y
are the coordinates of the point that will be the center of the written text. styles
The parameter is an object that can be used to set the values of a number of properties.
您可以使用样式设置字体 family
、size
和 alignment
等属性的值。您还可以指定以下属性的值 fill
、行程
、opacity
、rotation
、scale
和 translation
。
了解所有这些方法和属性后,是时候将它们应用到项目中了。在本教程中,我将向您展示如何使用 Two.js 渲染元素周期表的前十个元素,其中电子围绕原子核旋转。核也会有一些轻微的移动,以提高我们表示的视觉吸引力。
我们首先定义一些稍后将使用的变量和函数。
var centerX = window.innerWidth / 2; var centerY = window.innerHeight / 2; var elem = document.getElementById("atoms"); var elementNames = [ "", "Hydrogen", "Helium", "Lithium", "Beryllium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", "Neon" ]; var styles = { alignment: "center", size: 36, family: "Lato" }; var nucleusCount = 10; var nucleusArray = Array(); var electronCount = 10; var electronArray = Array(); function intRange(min, max) { return Math.random() * (max - min) + min; }
上面的代码将窗口中心的坐标存储在变量 centerX
和 centerY
中。稍后将使用它们将我们的原子放置在中心。 elementNames
数组包含元素周期表前十个元素的名称。每个名称的索引对应于该元素的电子和质子数,并且以空字符串开头。 styles
对象包含用于设置文本对象样式的属性。
我们还定义了一个函数 intRange()
来获取给定极值范围内的随机整数值。
var two = new Two({ fullscreen: true }).appendTo(elem); var protonColor = two.makeRadialGradient( 0, 0, 15, new Two.Stop(0, "red", 1), new Two.Stop(1, "black", 1) ); var neutronColor = two.makeRadialGradient( 0, 0, 15, new Two.Stop(0, "blue", 1), new Two.Stop(1, "black", 1) ); for (i = 0; i < nucleusCount; i++) { nucleusArray.push(two.makeCircle(intRange(-10, 10), intRange(-10, 10), 8)); } nucleusArray.forEach(function(nucleus, index) { if (index % 2 == 0) { nucleus.fill = protonColor; } if (index % 2 == 1) { nucleus.fill = neutronColor; } nucleus.noStroke(); });
这将创建 Two 的实例并定义两个径向渐变。红/黑径向渐变代表质子,蓝/黑渐变代表中子。
我们使用 intRange()
函数将所有这些中子和质子放置在彼此 20 像素以内。 makeCircle()
方法还将这些质子和中子的半径设置为 10 像素。之后,我们迭代 nucleusArray
并交替用不同的渐变填充每个圆圈。
for (var i = 0; i < 10; i++) { if (i < 2) { var shellRadius = 50; var angle = i * Math.PI; electronArray.push( two.makeCircle( Math.cos(angle) * shellRadius, Math.sin(angle) * shellRadius, 5 ) ); } if (i >= 2 && i < 10) { var shellRadius = 80; var angle = (i - 2) * Math.PI / 4; electronArray.push( two.makeCircle( Math.cos(angle) * shellRadius, Math.sin(angle) * shellRadius, 5 ) ); } }
将中子和质子放入原子核内很容易。然而,将电子正确地放置在均匀的距离需要一些数学知识。我们使用 shellRadius
变量来指定不同电子壳层距原子核的距离。整个圆所覆盖的角度等于 2 PI 弧度。我们可以通过在不同的电子之间均匀分布 2 PI 弧度来均匀地放置它们。
Math.cos()
和 Math.sin()
函数用于根据不同电子的位置向量分离垂直和水平分量他们的角度。
var orbitA = two.makeCircle(centerX, centerY, 50); orbitA.fill = "transparent"; orbitA.linewidth = 2; orbitA.stroke = "rgba(0, 0, 0, 0.1)"; var orbitB = two.makeCircle(centerX, centerY, 80); orbitB.fill = "transparent"; orbitB.linewidth = 2; orbitB.stroke = "rgba(0, 0, 0, 0.1)"; var groupElectronA = two.makeGroup(electronArray.slice(0, 2)); groupElectronA.translation.set(centerX, centerY); groupElectronA.fill = "orange"; groupElectronA.linewidth = 1; var groupElectronB = two.makeGroup(electronArray.slice(2, 10)); groupElectronB.translation.set(centerX, centerY); groupElectronB.fill = "yellow"; groupElectronB.linewidth = 1; var groupNucleus = two.makeGroup(nucleusArray); groupNucleus.translation.set(centerX, centerY);
这部分代码将来自不同壳层的电子以及中子和质子放入各自单独的组中。它还同时设置特定轨道中所有电子的填充颜色。
two .bind("update", function(frameCount) { groupElectronA.rotation += 0.025 * Math.PI; groupElectronB.rotation += 0.005 * Math.PI; groupNucleus.rotation -= 0.05; }) .play(); var text = two.makeText("", centerX, 100, styles); nucleusArray.forEach(function(nucleus, index) { nucleus.opacity = 0; }); electronArray.forEach(function(electron, index) { electron.opacity = 0; });
这部分代码将单个电子和质子的不透明度设置为零。它还告诉 Two.js 以特定速度旋转电子和质子。
visible = 0; document.addEventListener("click", function(event) { if (visible < nucleusArray.length) { nucleusArray[visible].opacity = 1; electronArray[visible].opacity = 1; visible++; text.value = elementNames[visible]; } else { nucleusArray.forEach(el => el.opacity=0); electronArray.forEach(el => el.opacity=0); visible = 0; text.value = elementNames[0]; } });
代码的最后部分允许我们通过单击鼠标或点击来迭代元素。为了加载下一个元素,我们再添加一个电子和一个质子或中子可见,并更新元素名称。单击最后一个元素后,所有粒子都会再次隐藏,以便我们可以重新开始。 visible
变量跟踪当前可见的原子粒子的数量,以便我们可以相应地显示或隐藏它们。
尝试单击或点击以下 CodePen 演示来查看元素周期表的前十个元素。
本教程首先简要介绍了 Two.js 库以及如何使用它来绘制矩形、圆形和椭圆形等形状。之后,我们讨论了如何对不同的对象进行分组以同时操作它们。我们利用这种能力对元素进行分组,以同步平移和旋转它们。这些工具全部集中在我们的元素周期表前十个元素的原子动画中。
如您所见,使用 Two.js 创建动画 2D 图形非常容易。这篇文章的重点是帮助您快速入门,因此我们只介绍了基础知识。但是,您应该阅读官方文档以了解有关该库的更多信息!
The above is the detailed content of Getting Started Creating 2D Graphics with Two.js: A Beginner's Guide. For more information, please follow other related articles on the PHP Chinese website!