跳到主要内容

React 如何绘制自定义图形?

要使用 react-konva 创建自定义图形,应使用 Shape 组件。

创建自定义图形时,需要定义一个传给 Konva.Canvas 渲染器的绘制函数。

可以通过渲染器访问 HTML5 Canvas 上下文,并使用 context.fillStrokeShape(shape) 等特殊方法。该方法会自动处理填充、描边和阴影。

import React from 'react';
import { Stage, Layer, Shape } from 'react-konva';

const App = () => {
  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <Shape
          width={260}
          height={170}
          sceneFunc={function (context, shape) {
            const width = shape.width();
            const height = shape.height();
            context.beginPath();
            context.moveTo(0, 0);
            context.lineTo(width - 40, height - 90);
            context.quadraticCurveTo(width - 110, height - 70, width, height);
            context.closePath();

            // (!) Konva specific method, it is very important
            context.fillStrokeShape(shape);
          }}
          fill="#00D2FF"
          stroke="black"
          strokeWidth={4}
        />
      </Layer>
    </Stage>
  );
};

export default App;