Skip to main content

如何使用 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 特定方法,非常重要
            context.fillStrokeShape(shape);
          }}
          fill="#00D2FF"
          stroke="black"
          strokeWidth={4}
        />
      </Layer>
    </Stage>
  );
};

export default App;