安装

npm install konva
1

官网案例

地址 open in new window


<!DOCTYPE html>
<html>
  <head>
    <script src="https://unpkg.com/konva@4.0.18/konva.min.js"></script>
    <meta charset="utf-8" />
    <title>Konva Stroke Demo</title>
    <style>
      body {
        margin: 0;
        padding: 0;
        overflow: hidden;
        background-color: #f0f0f0;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script>
      var width = window.innerWidth;
      var height = window.innerHeight;

      var stage = new Konva.Stage({
        container: 'container',
        width: width,
        height: height
      });
      var layer = new Konva.Layer();

      var pentagon = new Konva.RegularPolygon({
        x: stage.width() / 2,
        y: stage.height() / 2,
        sides: 5,
        radius: 70,
        fill: 'red',
        stroke: 'black',
        strokeWidth: 4
      });

      pentagon.on('mouseover', function() {
        this.stroke('blue');
        this.strokeWidth(20);
        layer.draw();
      });

      pentagon.on('mouseout', function() {
        this.stroke('black');
        this.strokeWidth(4);
        layer.draw();
      });
      // add the shape to the layer
      layer.add(pentagon);

      // add the layer to the stage
      stage.add(layer);
    </script>
  </body>
</html>

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

Konva 是什么?

Konva 是一个HTML5 Canvas JavaScript 框架,它通过对 2d context 的扩展实现了在桌面端和移动端的可交互性。Konva 提供了高性能的动画,补间,节点嵌套,布局,滤镜,缓存,事件绑定(桌面/移动端)等等功能。你可以使用 Konva 在舞台上绘制图形,给图形添加事件,移动、缩放和旋转图形并且支持高性能的动画即使包含数千个图形。

工作原理?

Konva 的对象是以一颗树的形式保存的,Konva.Stage 是树的根节点,Stage 子节点是用户创建的图层 (Konva.Layer)。

每一个 layer 有两个 渲染器: 场景渲染器 和 图像命中检测渲染器。场景渲染器输出你所看见的内容,图像命中渲染器在隐藏的 canvas 里用于高性能的检测事件。

图层可以包含图形、嵌套图形的组、嵌套组的组。Stage(舞台),layers(图层),groups(组),和 shapes(图形) 都是虚拟节点,类似于 HTML 的 DOM 节点。

节点结构图:

              Stage
                |
         +------+------+
         |             |
       Layer         Layer
         |             |
   +-----+-----+     Shape
   |           |
 Group       Group
   |           |
   +       +---+---+
   |       |       |
Shape   Group    Shape
           |
           +
           |
         Shape

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

你可以对所有节点修改样式和变换。Konva 内建了很多图形,例如:rectangles, circles, images, sprites, text, lines, polygons, regular polygons, paths, stars等等,也可以通过实例化 Shape class 和自定义 draw function 创建自定义图形。

创建好了stage、layers 和 shapes 后,你就能进行绑定事件,变换节点,运行动画,添加滤镜等等操作了。