跳到主要内容

HTML5 Canvas 自定义图形教程

要使用 Konva 创建自定义图形,可以使用 Konva.Shape() 对象并定义自定义绘制函数。

创建自定义图形时,需要定义一个绘制函数。该函数接收一个 Konva.Context 渲染器和一个图形实例。下面是一个简单的矩形示例:

const rect = new Konva.Shape({
x: 10,
y: 20,
fill: '#00D2FF',
width: 100,
height: 50,
sceneFunc: function (context, shape) {
context.beginPath();
// don't need to set position of rect, Konva will handle it
context.rect(0, 0, shape.getAttr('width'), shape.getAttr('height'));
// (!) Konva specific method, it is very important
// it will apply all required styles
context.fillStrokeShape(shape);
}
});

Konva.Context 是原生 2D Canvas 上下文的封装。它具有相同的属性和方法,还提供了一些附加 API。

有两个属性可用于绘制自定义图形:

  • sceneFunc - 定义图形的视觉外观
  • hitFunc - 可选函数,用于定义事件的自定义命中区域(请参阅自定义命中区域示例

编写 sceneFunchitFunc 的最佳实践:

  1. 优化该函数,因为它每秒可能调用多次。不要创建图像或大型对象。
  2. 该函数不得产生移动图形、绑定事件或更改应用的 state 等副作用。
  3. 应用复杂样式或绘制图像时,请定义自定义 hitFunc
  4. 不要在 sceneFunc 中手动应用位置和缩放。让 Konva 通过图形属性处理这些变换。
  5. 不要在 sceneFunc 中手动设置样式。使用 context.fillStrokeShape(shape) 设置样式。
  6. 有关更多示例,请参阅 Konva 核心图形实现

有关完整的属性和方法列表,请参阅 Shape API 参考

import Konva from 'konva';

const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight
});

const layer = new Konva.Layer();
stage.add(layer);

const triangle = new Konva.Shape({
  sceneFunc: function (context, shape) {
    context.beginPath();
    context.moveTo(20, 50);
    context.lineTo(220, 80);
    context.lineTo(100, 150);
    context.closePath();
    context.fillStrokeShape(shape);
  },
  fill: '#00D2FF',
  stroke: 'black',
  strokeWidth: 4
});

layer.add(triangle);