search
HomeWeb Front-endJS TutorialGetting Started Creating 2D Graphics with Two.js: A Beginner's Guide

使用 Two.js 创建 2D 图形入门:初学者指南

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.

  • Create basic shapes
  • Objects in the operation group
  • Define gradients and write text
  • Create Two.js project

Install

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.

Create basic shapes

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.

You can also use

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.

Arrows can also be easily created with the help of the

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.

There is a method called

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

A useful method in Two.js that you will often use is

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.

Define gradients and write text

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.

您可以使用样式设置字体 familysizealignment 等属性的值。您还可以指定以下属性的值 fill行程opacityrotationscaletranslation

创建 Two.js 项目

了解所有这些方法和属性后,是时候将它们应用到项目中了。在本教程中,我将向您展示如何使用 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;
}

上面的代码将窗口中心的坐标存储在变量 centerXcenterY 中。稍后将使用它们将我们的原子放置在中心。 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 图形非常容易。这篇文章的重点是帮助您快速入门,因此我们只介绍了基础知识。但是,您应该阅读官方文档以了解有关该库的更多信息!

更多 JavaScript 资源

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools