Konva
Konva 是 HTML5 Canvas 的 JavaScript 框架,它可以為桌面或行動應用的網頁提供方便高效的繪圖能力。
如何運作
- 一切從
Konva.Stage
開始 - Konva.Stage 可以包含許多的圖層 (
Konva.Layer
) - 每個圖層可以包含許多形狀 (
Konva.Shape
) 或群組 (Konva.Group
) - 每個群組可以包含許多形狀 (
Konva.Shape
) 或其他群組 (Konva.Group
)
- 在使用 Konva 前,要先插入以下代碼:
<script src="https://unpkg.com/konva@3.4.1/konva.min.js"></script>
1
範例
使用 Konva 畫一個圓。
HTML 部份:插入使用 Konva 的代碼,並準備要給 Konva 使用的元素。 (該元素要設定一個 id)
<h2>Konva's Circle</h2>
<script src="https://unpkg.com/konva@3.4.1/konva.min.js"></script>
<div id="container"></div>
1
2
3
2
3
JS 部份:加入以下代碼:
// first we need to create a stage
var stage = new Konva.Stage({
container: 'container', // id of container <div>
width: 160,
height: 160
});
// then create a layer
var layer = new Konva.Layer();
// create our shape
var circle = new Konva.Circle({
x: stage.width() / 2, // x position of the center
y: stage.height() / 2, // y position of the center
radius: 70, // circle radius
fill: 'red', // color to fill the area
stroke: 'black', // color to draw the line
strokeWidth: 4 // line width
});
// add the shape to the layer
layer.add(circle);
// add the layer to the stage
stage.add(layer);
// draw the image
layer.draw();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
結果
練習
試著改變圓的屬性,例如填充顏色、邊界顏色、大小等。
← JavaScript 基本圖形 →