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- 可选函数,用于定义事件的自定义命中区域(请参阅自定义命中区域示例)
编写 sceneFunc 和 hitFunc 的最佳实践:
- 优化该函数,因为它每秒可能调用多次。不要创建图像或大型对象。
- 该函数不得产生移动图形、绑定事件或更改应用的 state 等副作用。
- 应用复杂样式或绘制图像时,请定义自定义
hitFunc。 - 不要在
sceneFunc中手动应用位置和缩放。让 Konva 通过图形属性处理这些变换。 - 不要在
sceneFunc中手动设置样式。使用context.fillStrokeShape(shape)设置样式。 - 有关更多示例,请参阅 Konva 核心图形实现。
有关完整的属性 和方法列表,请参阅 Shape API 参考。
- Vanilla
- React
- Vue
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);
import { Stage, Layer, Shape } from 'react-konva';
const App = () => {
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Shape
sceneFunc={(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>
</Stage>
);
};
export default App;
<template>
<v-stage :config="stageSize">
<v-layer>
<v-shape :config="shapeConfig" />
</v-layer>
</v-stage>
</template>
<script setup>
const stageSize = {
width: window.innerWidth,
height: window.innerHeight
};
const shapeConfig = {
sceneFunc: (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
};
</script>