Home >Web Front-end >JS Tutorial >Getting Started with Paper.js: Paths and Geometry

Getting Started with Paper.js: Paths and Geometry

WBOY
WBOYOriginal
2023-08-30 20:25:131276browse

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);

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;

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);

在上面的代码中,我首先使用上面讨论的 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); 

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

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();

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:
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