search
HomeWeb Front-endJS TutorialWorking with HTML5 Canvas with Konva: Exploring Basic Shapes (Part 2)

使用 Konva 操作 HTML5 Canvas:探索基本形状(第 2 部分)

This series of introductory tutorials teaches you how to draw your first shape using Konva. It also explains how layers and groups work in Konva. In the remainder of this series, we'll focus on more specific topics, such as creating basic and complex shapes or attaching event listeners to different shapes to make graphics interactive.

This special tutorial will show you how to create basic shapes like rectangles, circles, and ovals in Konva. You'll also learn about the different properties you can use to customize the appearance of all these shapes to suit your needs. The remainder of this tutorial will discuss how to draw different types of lines and regular polygons using Konva.

Draw rectangles, circles and ovals

You can create rectangles in Konva using the Konva.rect() object. You can specify the position of the upper left corner of the rectangle using the x and y properties. Likewise, you can specify the width and height of a rectangle using the width and height properties. By default, all rectangles you draw will have sharp corners. However, you can make them round by choosing an appropriate value for the cornerRadius property.

You can use the visible property to show or hide the rectangle. If you don't want to completely hide the rectangle but still make it semi-transparent, you can use the opacity property. You can set this to any number between 0 and 1, inclusive. If the opacity is set to 0, the shape will not be visible.

You can also rotate or scale a rectangular shape using the rotation and scale properties respectively. The rotation is specified as an ordinary number but is applied in degrees. You can optionally scale any rectangle on the x or y axis independently using the scaleX and scaleY properties.

Here is an example of drawing different rectangles on the canvas using all the properties we just discussed.

var canvasWidth = 600;
var canvasHeight = 400;

var stage = new Konva.Stage({
  container: "example",
  width: canvasWidth,
  height: canvasHeight
});

var layerA = new Konva.Layer();

var rectA = new Konva.Rect({
  x: 10,
  y: 10,
  width: 200,
  height: 50,
  fill: "yellow",
  stroke: "black"
});

var rectB = new Konva.Rect({
  x: 160,
  y: 30,
  width: 80,
  height: 250,
  fill: "orange",
  stroke: "black"
});

var rectC = new Konva.Rect({
  x: 200,
  y: 160,
  width: 180,
  height: 180,
  cornerRadius: 10,
  strokeWidth: 10,
  opacity: 0.8,
  fill: "red",
  stroke: "black"
});

var rectD = new Konva.Rect({
  x: 400,
  y: 20,
  width: 180,
  height: 180,
  scaleX: 1.8,
  scaleY: 0.75,
  rotation: 45,
  fill: "lightgreen",
  stroke: "black"
});

layerA.add(rectA, rectB, rectC, rectD);

stage.add(layerA);

You should note that the rectangles are not drawn in the order they are created. Instead, they are drawn in the order they are added to the layers. The fill and Stroke properties are used to set the fill and stroke colors respectively.

You can create circles in Konva using the Konva.circle() object. This time, the x and y properties determine the center point of the drawn circle. You can still specify a value for the width and height properties. These values ​​are used to calculate the diameter of the circle to be drawn. However, the width and height of a circle are equal. This means that, in the event of a conflict, the value specified later takes precedence over the value specified earlier. In other words, if you set a circle's width to 100 and then set its height to 180, the circle's diameter will be 180 and the width will be ignored.

To avoid confusion, you can omit the width and height properties and specify a value for the circle's radius. Remember that you must set the radius to 50 to draw a circle with a width and height of 100.

In a similar way, you can also create ellipses using the Konva.ellipse() object. The only difference is that the radius property now accepts an object with x and y properties as its value. If specified, the width and height properties are now applied independently to determine the final shape of the ellipse.

var canvasWidth = 600;
var canvasHeight = 400;

var stage = new Konva.Stage({
  container: "example",
  width: canvasWidth,
  height: canvasHeight
});

var layerA = new Konva.Layer();

var circA = new Konva.Circle({
  x: 100,
  y: 100,
  width: 180,
  fill: "yellow",
  stroke: "black"
});

var circB = new Konva.Circle({
  x: 180,
  y: 150,
  height: 100,
  fill: "orange",
  stroke: "black"
});

var circC = new Konva.Circle({
  x: 200,
  y: 275,
  radius: 100,
  opacity: 0.5,
  fill: "red",
  stroke: "black"
});

var ellipA = new Konva.Ellipse({
  x: 400,
  y: 75,
  width: 70,
  height: 100,
  rotation: -15,
  fill: "lightgreen",
  stroke: "black"
});

var ellipB = new Konva.Ellipse({
  x: 400,
  y: 75,
  width: 80,
  height: 120,
  rotation: -15,
  strokeWidth: 5,
  fill: "white",
  stroke: "black"
});

var ellipC = new Konva.Ellipse({
  x: 450,
  y: 275,
  radius: {
    x: 100,
    y: 50
  },
  scaleY: 2,
  fill: "violet",
  stroke: "black"
});

layerA.add(circA, circB, circC, ellipB, ellipA, ellipC);

stage.add(layerA);

You should note that ellipB has a larger height and width compared to ellipA. Since they both have the same x and y values, I have to add ellipB to the layer first to keep ellipA visible. If ellipB is added after ellipA, it will be drawn over ellipA, thus hiding it from the viewer.

If you look closely, you'll also see that the purple circle is actually an oval, with the y radius set to 50 and the x radius set to 100. However, it is scaled by a factor of 2 in the y direction. Scaling also increases the stroke width so that it is twice wider at the top and bottom of the ellipse than at its left and right edges.

使用 Konva 绘制线条

您可以使用 Konva.Line() 对象来创建不同类型的直线和曲线。所有线都要求您使用 points 属性指定线应经过的点。这些点被指定为数组。

您可以通过将 close 属性的值设置为 true 来连接使用 points 数组提供的任何点集来形成多边形。同样,您可以通过设置 tension 属性的值将一组直线转换为样条线。零值将产生直线。值越高,线条越弯曲。

您可以通过设置 tension 属性的值来创建闭合且弯曲的形状(斑点),并通过设置 lined 来闭合曲线到 true

与我们讨论过的其他形状一样,您可以使用 StrokeWidth 属性设置绘制线条的描边宽度。您还可以为闭合形状指定 fill 颜色。

在下面的示例中,我使用同一组点来绘制所有形状。但是,我还使用 move() 方法将每个形状移动特定的距离,以避免重叠。

var canvasWidth = 600;
var canvasHeight = 400;

var stage = new Konva.Stage({
  container: "example",
  width: canvasWidth,
  height: canvasHeight
});

var layerA = new Konva.Layer();

var lineA = new Konva.Line({
  points: [50, 20, 20, 100, 80, 140, 60, 80, 200, 20],
  stroke: "black"
});

var lineB = new Konva.Line({
  points: [50, 20, 20, 100, 80, 140, 60, 80, 200, 20],
  closed: true,
  fill: "yellow",
  stroke: "black"
});

var lineC = new Konva.Line({
  points: [50, 20, 20, 100, 80, 140, 60, 80, 200, 20],
  tension: 0.8,
  stroke: "blue"
});

var lineD = new Konva.Line({
  points: [50, 20, 20, 100, 80, 140, 60, 80, 200, 20],
  tension: 1.8,
  stroke: "red"
});

var lineE = new Konva.Line({
  points: [50, 20, 20, 100, 80, 140, 60, 80, 200, 20],
  closed: true,
  tension: 2.2,
  fill: "lightblue",
  stroke: "black"
});

lineB.move({
  x: 180,
  y: 40
});

lineC.move({
  x: 380,
  y: 0
});

lineD.move({
  x: 0,
  y: 200
});

lineE.move({
  x: 180,
  y: 220
});

layerA.add(lineA, lineB, lineC, lineD, lineE);

stage.add(layerA);

您还应该注意,红线和蓝线是使用同一组点绘制的,但不同的 tension 值会显着改变曲线的最终形状。

绘制正多边形

您可以仔细选择points数组中不同点的值来绘制五边形和六边形等正多边形。使用此方法绘制更复杂的正多边形(例如八边形)可能很麻烦且容易出错。为了避免错误,您应该使用 Konva.RegularPolygon() 对象来创建正多边形。

xy 属性用于指定多边形的中心。 radius 属性用于指定多边形中心点与其所有顶点之间的距离。您可以使用 sides 属性来指定多边形应具有的边数。请记住,使用此方法创建的多边形的所有边都具有相等的长度。您可以使用 scaleXscaleY 属性更改某些边的长度,但它也会更改缩放边的描边宽度。

就像我们讨论过的所有其他形状一样,您可以使用 行程宽度opacity可见性

var canvasWidth = 600;
var canvasHeight = 400;

var stage = new Konva.Stage({
  container: "example",
  width: canvasWidth,
  height: canvasHeight
});

var layerA = new Konva.Layer();

var triangle = new Konva.RegularPolygon({
  x: 150,
  y: 275,
  sides: 3,
  radius: 100,
  scaleY: 1.6,
  stroke: "black",
  fill: "rgba(200,0,200, 1)",
});

var square = new Konva.RegularPolygon({
  x: 60,
  y: 60,
  sides: 4,
  radius: 50,
  fill: "rgba(200,0,0, 0.5)",
  stroke: "black"
});

var pentagon = new Konva.RegularPolygon({
  x: 160,
  y: 160,
  sides: 5,
  radius: 80,
  fill: "rgba(0,200,0, 0.5)",
  stroke: "black"
});

var hexagon = new Konva.RegularPolygon({
  x: 350,
  y: 120,
  sides: 6,
  radius: 80,
  fill: "rgba(0,0,200, 0.5)",
  stroke: "black"
});

var octagon = new Konva.RegularPolygon({
  x: 450,
  y: 275,
  sides: 8,
  radius: 100,
  fill: "rgba(200,200,0, 0.5)",
  stroke: "black"
});

layerA.add(triangle, square, pentagon, hexagon, octagon);

stage.add(layerA);

最终想法

在本教程中,我们介绍了 Konva 允许我们轻松在画布上绘制的最基本形状。我们还了解了可用于控制所有这些形状的外观的不同属性。大多数属性对于所有形状都是通用的,但其中一些属性仅适用于特定形状。

如果您有任何疑问,请在评论中告诉我。我们将在本系列的下一个教程中了解一些更复杂的形状。

The above is the detailed content of Working with HTML5 Canvas with Konva: Exploring Basic Shapes (Part 2). 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
JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

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

Video Face Swap

Video Face Swap

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

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function