Table of Contents
Use path
Predefined shapes
Simplify and Flatten Paths
几何和数学
最终想法
Home Web Front-end JS Tutorial Getting Started with Paper.js: Paths and Geometry

Getting Started with Paper.js: Paths and Geometry

Aug 30, 2023 pm 08:25 PM
path Geometry paperjs

Getting Started with Paper.js: Paths and Geometry

In the previous tutorial, I introduced the installation process and project hierarchy in Paper.js. This time I will teach you about paths, line segments and their operations. This will enable you to create complex shapes using the library. After that, I want to introduce some basic geometric principles on which Paper.js is based.

Use path

A path in Paper.js is represented by a series of line segments connected by curved lines. A segment is basically a point and its two handles, which define the position and direction of the curve. Not defining line segments results in straight lines rather than curves.

After defining a new path using the new Path() constructor, you can add segment functionality to it with the help of path.add(segment). Since this function supports multiple parameters, you can also add multiple segments at once. Suppose you want to insert a new segment at a specific index within an existing path. You can do this using the path.insert(index, segment) function. Likewise, to remove a segment at a specific index, you can use the path.removeSegment(index) function. Both functions use zero-based indexing. This means that using path.removeSegment(3) will remove the fourth segment. You can turn off all drawn paths using the path.lated property. It will connect the first and last segments of the path together.

So far, all our paths have been straight lines. To create a curved path without specifying a handle for each segment, you can use the path.smooth() function. This function calculates the optimal value of the handles for all segments in the path so that the curve passing through them is smooth. The segments themselves do not change their positions, and if you specify handle values ​​for any segments, these values ​​are ignored. The code below uses all the functions and properties we discussed to create four paths, two of which are curved.

var aPath = new Path();
aPath.add(new Point(30, 60));
aPath.add(new Point(100, 200));
aPath.add(new Point(300, 280), new Point(280, 40));
aPath.insert(3, new Point(180, 110));
aPath.fullySelected = 'true';
aPath.closed = true;
  
var bPath = aPath.clone();
bPath.smooth();
bPath.position.x += 400;
  
var cPath = aPath.clone();
cPath.position.y += 350;
cPath.removeSegment(3);
  
var dPath = bPath.clone();
dPath.strokeColor = 'green';
dPath.position.y += 350;
dPath.removeSegment(3);
Copy after login

First, we create a new path and then add segments to it. Use path.insert(3, new Point(180, 110)) to insert a new segment in place of the fourth segment and move the fourth segment to the fifth position. I've set fullySelected to true to show all points and handles of each curve. For the second path, I used the path.smooth() function to smooth the curve. Removing the fourth segment using cPath.removeSegment(3) gives us the original shape without any index-based insertion. You can verify this by commenting out aPath.insert(3, new Point(180, 110)); in this CodePen demo. Here’s the end result of everything we’ve done so far:

<图>

Predefined shapes

Paper.js supports some basic shapes out of the box. For example, to create a circle, you can simply use the new Path.Circle(center, radius) constructor. Likewise, you can use the new Path.Rectangle(rect) constructor to create a rectangle. You can specify the upper left corner and lower right corner, or you can specify the upper left corner and the size of the rectangle. To draw a rounded rectangle, you can use the new Path.RoundedRectangle(rect, size) constructor, where the size parameter determines the size of the rounded corners.

If you want to create an n-sided regular polygon, you can use the new Path.RegularPolygon(center, numSides, radius) constructor. Parameter center determines the center of the polygon, and radius determines the radius of the polygon.

The code below will generate all the shapes we just discussed.

var aCircle = new Path.Circle(new Point(75, 75), 60);
aCircle.strokeColor = 'black';
  
var aRectangle = new Path.Rectangle(new Point(200, 15), new Point(400, 135));
aRectangle.strokeColor = 'orange';
  
var bRectangle = new Path.Rectangle(new Point(80, 215), new Size(400, 135));
bRectangle.strokeColor = 'blue';
  
var myRectangle = new Rectangle(new Point(450, 30), new Point(720, 170));
var cornerSize = new Size(10, 60);
var cRectangle = new Path.RoundRectangle(myRectangle, cornerSize);
cRectangle.fillColor = 'lightgreen';
  
var aTriangle = new Path.RegularPolygon(new Point(120, 500), 3, 110);
aTriangle.fillColor = '#FFDDBB';
aTriangle.selected = true;

var aDodecagon = new Path.RegularPolygon(new Point(460, 490), 12, 100);
aDodecagon.fillColor = '#CCAAFC';
aDodecagon.selected = true;
Copy after login

The first rectangle we create is based on coordinate points. Next use the first point to determine the top left corner of the rectangle, then use the size value to draw the remaining points. In the third rectangle, we also specify the radius of the rectangle. The first radius parameter determines the horizontal curvature, and the second parameter determines the vertical curvature.

The last two shapes simply use the RegularPolygon constructor to create triangles and dodecagons. The embedded demo below shows the results of our code.

<图>

Simplify and Flatten Paths

There are two ways to create a circle. The first is to create many segments without any handles and place them closely together. This way, although they will be connected by straight lines, the overall shape will still be closer to a circle. The second method is to use only four segments and set appropriate values ​​for their handles. This saves a lot of memory and still gives us the desired results.

大多数时候,我们可以从路径中删除相当多的线段,而不会显着改变其形状。该库提供了一个简单的 path.simplify([tolerance]) 函数来实现此结果。容差参数是可选的。它用于指定路径简化算法可以偏离其原始路径的最大距离。默认设置为 2.5。如果将该参数设置为较高的值,最终的曲线会更平滑一些,段点也会较少,但偏差可能会很大。同样,较低的值将导致非常小的偏差,但会包含更多的段。

您还可以使用 path.flatten(maxDistance) 函数将路径中的曲线转换为直线。在展平路径时,库会尝试使段之间的距离尽可能接近 maxDistance

var aPolygon = new Path.RegularPolygon(new Point(140, 140), 800, 120);
aPolygon.fillColor = '#CCAAFC';
aPolygon.selected = true;
  
var bPolygon = aPolygon.clone();
bPolygon.fillColor = '#CCFCAA';
bPolygon.simplify();
  
var cPolygon = aPolygon.clone();
cPolygon.fillColor = '#FCAACC';
cPolygon.simplify(4);
  
var dPolygon = bPolygon.clone();
dPolygon.fillColor = '#FCCCAA';
dPolygon.flatten(80);
Copy after login

在上面的代码中,我首先使用上面讨论的 RegularPolygon 函数创建了一个多边形。我特意将 selected 属性设置为 true ,以便这些路径中的所有段都可见。然后,我从第一个多边形中克隆了第二个多边形,并在其上使用了 simplify 函数。这将段数减少到只有五个。

在第三个多边形中,我将公差参数设置为更高的值。这进一步减少了段的数量。您可以看到所有路径仍然具有相同的基本形状。在最后的路径中,我使用了 flatten(maxDistance) 函数来展平我们的曲线。该算法尝试使形状尽可能接近原始形状,同时仍然遵守 maxDistance 约束。最终结果如下:

<图>

几何和数学

Paper.js 有一些基本数据类型,如 PointSizeRectangle 来描述图形项的几何属性。它们是几何值(如位置或尺寸)的抽象表示。点只是描述二维位置,大小描述二维空间中的抽象维度。这里的矩形表示由左上角点及其宽度和高度围成的区域。它与我们之前讨论的矩形路径不同。与路径不同,它不是一个项目。您可以在这个 Paper.js 教程中了解有关它们的更多信息。

您可以对点数和大小执行基本的数学运算 - 加法、减法、乘法和除法。以下所有操作均有效:

var pointA = new Point(20, 10);

var pointB = pointA * 3; // { x: 60, y: 30 }
var pointC = pointB - pointA; // { x: 40, y: 20 }
var pointD = pointC + 30; // { x: 70, y: 50 }
var pointE = pointD / 5;  // { x: 14, y: 10 }
var pointF = pointE * new Point(3, 2); // { x: 42, y: 20 }

// You can check the output in console for verification
console.log(pointF); 
Copy after login

除了这些基本操作之外,您还可以执行一些舍入操作或生成点和大小的随机值。考虑以下示例:

var point = new Point(3.2, 4.7);

var rounded = point.round(); // { x: 3, y: 5 }
var ceiled  = point.ceil();  // { x: 4, y: 5 }
var floored = point.floor(); // { x: 3, y: 4 }

// Generate a random point with x between 0 and 50
// and y between 0 and 40
var pointR = new Point(50, 40) * Point.random();

// Generate a random size with width between 0 and 50
// and height between 0 and 40
var sizeR = new Size(50, 40) * Size.random();
Copy after login

random() 函数生成 0 到 1 之间的随机值。您可以将它们与适当的 PointSize 对象相乘值以获得所需的结果。

这总结了您需要熟悉的基本数学知识,以使用 Paper.js 创建有用的内容。

最终想法

完成本教程后,您应该能够创建各种路径和形状、展平曲线或简化复杂路径。现在您对可以使用 Paper.js 执行的各种数学运算也有了基本的了解。通过结合您在本系列教程和上一个教程中学到的所有内容,您应该能够在不同图层上创建复杂的多边形并将它们混合在一起。您还应该能够在路径中插入和删除线段以获得所需的形状。

如果您正在寻找其他 JavaScript 资源来学习或在工作中使用,请查看我们在 Envato 市场中提供的资源。

如果您对本教程有任何疑问,请在评论中告诉我。

The above is the detailed content of Getting Started with Paper.js: Paths and Geometry. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where are themes located in Windows 11? Where are themes located in Windows 11? Aug 01, 2023 am 09:29 AM

Windows 11 has so many customization options, including a range of themes and wallpapers. While these themes are aesthetic in their own way, some users still wonder where they stand in the background on Windows 11. This guide will show you the different ways to access the location of your Windows 11 theme. What is the Windows 11 default theme? The default theme background of Windows 11 is an abstract royal blue flower blooming with a sky blue background. This background is one of the most popular, thanks to the anticipation before the release of the operating system. However, the operating system also comes with a range of other backgrounds. Therefore, you can change the Windows 11 desktop theme background at any time. Themes are stored in Windo

Different uses of slashes and backslashes in file paths Different uses of slashes and backslashes in file paths Feb 26, 2024 pm 04:36 PM

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

How to fix error: Main class not found or loaded in Java How to fix error: Main class not found or loaded in Java Oct 26, 2023 pm 11:17 PM

This video cannot be played due to a technical error. (Error Code: 102006) This guide provides simple fixes for this common problem and continue your coding journey. We will also discuss the causes of Java errors and how to prevent it in the future. What is "Error: Main class not found or loaded" in Java? Java is a powerful programming language that enables developers to create a wide range of applications. However, its versatility and efficiency come with a host of common mistakes that can occur during development. One of the interrupts is Error: Main class user_jvm_args.txt not found or loaded, which occurs when the Java Virtual Machine (JVM) cannot find the main class to execute a program. This error acts as a roadblock even in

What is the difference in the 'My Computer' path in Win11? Quick way to find it! What is the difference in the 'My Computer' path in Win11? Quick way to find it! Mar 29, 2024 pm 12:33 PM

What is the difference in the "My Computer" path in Win11? Quick way to find it! As the Windows system is constantly updated, the latest Windows 11 system also brings some new changes and functions. One of the common problems is that users cannot find the path to "My Computer" in Win11 system. This was usually a simple operation in previous Windows systems. This article will introduce how the paths of "My Computer" are different in Win11 system, and how to quickly find them. In Windows1

Get the directory portion of a file path using the path/filepath.Dir function Get the directory portion of a file path using the path/filepath.Dir function Jul 27, 2023 am 09:06 AM

Use the path/filepath.Dir function to obtain the directory part of the file path. In our daily development process, file path processing is often involved. Sometimes, we need to get the directory part of the file path, that is, the path to the folder where the file is located. In the Go language, you can use the Dir function provided by the path/filepath package to implement this function. The signature of the Dir function is as follows: funcDir(pathstring)string The Dir function receives a word

Linux kernel source code storage path analysis Linux kernel source code storage path analysis Mar 14, 2024 am 11:45 AM

The Linux kernel is an open source operating system kernel whose source code is stored in a dedicated code repository. In this article, we will analyze the storage path of the Linux kernel source code in detail, and use specific code examples to help readers better understand. 1. Linux kernel source code storage path The Linux kernel source code is stored in a Git repository called linux, which is hosted at [https://github.com/torvalds/linux](http

How to find the storage path of RPM files in Linux system? How to find the storage path of RPM files in Linux system? Mar 14, 2024 pm 04:42 PM

In Linux systems, RPM (RedHatPackageManager) is a common software package management tool used to install, upgrade and delete software packages. Sometimes we need to find the storage path of an installed RPM file for search or other operations. The following will introduce how to find the storage path of the RPM file in the Linux system, and provide specific code examples. First, we can use the rpm command to find the installed RPM package and its storage path. Open

How to use the os.path module to obtain various parts of the file path in Python 3.x How to use the os.path module to obtain various parts of the file path in Python 3.x Jul 30, 2023 pm 02:57 PM

How to use the os.path module in Python3.x to obtain various parts of the file path. In daily Python programming, we often need to operate on the file path, such as obtaining the file name, file directory, extension, etc. of the path. In Python, you can use the os.path module to perform these operations. This article will introduce how to use the os.path module to obtain various parts of the file path for better file manipulation. The os.path module provides a series of

See all articles