除了官方内置的图形以外,我们可以通过 Konva.Shape
类自定义图形,如下所示:
const stage = new Konva.Stage({
container: "container",
width: window.innerWidth,
height: window.innerHeight
});
const layer = new Konva.Layer();
const custRect = new Konva.Shape({
x: 10,
y: 10,
fill: "#00D2FF",
width: 200,
height: 100,
sceneFunc: function (context, shape) {
context.beginPath();
context.rect(0, 0, shape.getAttr("width"), shape.getAttr("height"));
context.fillStrokeShape(shape);
}
});
layer.add(custRect);
stage.add(layer);
最重要的是 sceneFunc
属性,通过这个属性我们定义的一个函数会返回两个参数,context 和 shape。context 与原生 2D Canvas 的 API 是一样的。
在 context beginPath 之后,结尾处需要通过一个特别的函数 fillStrokeShape
来渲染自定义的 Konva 图形到 Canvas 中。