Skip to main content

如何从 react-konva 导出画布为图像?

如何保存来自 react-konva 的绘图?

要将任何 Konva 节点导出为图像,您可以使用 node.toDataURL()node.toImage() API。请查看 原生 Konva 图像导出演示

您需要使用 Refs API 直接访问 Konva 节点,以便调用这些方法。

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

// 来自 https://stackoverflow.com/a/15832662/512042 的函数
function downloadURI(uri, name) {
  var link = document.createElement('a');
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

const App = () => {
  const width = window.innerWidth;
  const height = window.innerHeight;

  const stageRef = React.useRef(null);

  const handleExport = () => {
    const uri = stageRef.current.toDataURL();
    console.log(uri);
    // 我们还可以将 uri 保存为文件
    downloadURI(uri, 'stage.png');
  };

  return (
    <Fragment>
      <button onClick={handleExport}>点击此处将舞台导出为图像</button>
      <Stage width={width} height={height} ref={stageRef}>
        <Layer>
          <Rect x={0} y={0} width={80} height={80} fill="red" />
          <Rect x={width - 80} y={0} width={80} height={80} fill="red" />
          <Rect
            x={width - 80}
            y={height - 80}
            width={80}
            height={80}
            fill="red"
          />
          <Rect x={0} y={height - 80} width={80} height={80} fill="red" />
        </Layer>
      </Stage>
    </Fragment>
  );
};

export default App;