Fabric.js 和react、sendBackward 和bringForward 被报告为不具有功能,尽管其他结构选项/功能正在工作

问题描述 投票:0回答:1

这是一个 React/Fabric.js 测试,我正在尝试找出在堆栈中移动对象时我做错了什么。画布初始化以及红色和蓝色框在那里,可以使用小控件操作它们,并且preserveObjectStacking正在工作,但是bringForward和sendBackward都报告没有这样的函数,这些是画布函数,是吗?它们在文档中,但总是错误“*不是函数” 任何帮助将不胜感激。

import React, { useEffect, useRef, useState } from 'react';
import { Canvas, Rect } from 'fabric';

const FabricCanvasTest = () => {
  const canvasRef = useRef(null);
  const [canvas, setCanvas] = useState(null);
  const [activeObject, setActiveObject] = useState(null);

  useEffect(() => {
    const initCanvas = new Canvas(canvasRef.current, {
      width: 400,
      height: 400,
      backgroundColor: '#f0f0f0',
      preserveObjectStacking: true,
    });

    const redSquare = new Rect({
      left: 50,
      top: 50,
      fill: 'red',
      width: 100,
      height: 100
    });

    const blueSquare = new Rect({
      left: 200,
      top: 200,
      fill: 'blue',
      width: 100,
      height: 100
    });

    initCanvas.add(redSquare, blueSquare);
    setCanvas(initCanvas);

    initCanvas.on('selection:created', (e) => setActiveObject(e.selected[0]));
    initCanvas.on('selection:updated', (e) => setActiveObject(e.selected[0]));
    initCanvas.on('selection:cleared', () => setActiveObject(null));

    return () => {
      initCanvas.dispose();
    };
  }, []);

  const bringForward = () => {
    if (activeObject) {
      activeObject.bringForward();
      canvas.renderAll();
    }
  };

  const sendBackward = () => {
    if (activeObject) {
      activeObject.sendBackwards();
      canvas.renderAll();
    }
  };

  return (
    <div>
      <canvas ref={canvasRef} />
      <div>
        <button onClick={bringForward} disabled={!activeObject}>Bring Forward</button>
        <button onClick={sendBackward} disabled={!activeObject}>Send Backward</button>
      </div>
      <p>
        {activeObject
          ? `Selected: ${activeObject.fill} square`
          : 'No object selected'}
      </p>
    </div>
  );
};

export default FabricCanvasTest;
javascript reactjs fabricjs fabric
1个回答
0
投票

我不知道为什么'fabric.js'的官方API文档与它实现的实际接口不一致。 有一些我用过的功能,你可以尝试一下:

 const bringForward = () => {
      if (activeObject) {
      // bring to topmost
      // canvas.bringObjectToFront(activeObject)
      canvas.bringObjectForward(activeObject, true);
      canvas.renderAll();
    }
  };

const sendBackward = () => {
    if (activeObject) {
      // send to bottom 
      // canvas.sendObjectBackwards(activeObject)
      canvas.sendObjectToBack(activeObject, true);
      canvas.renderAll();
    }
  };
© www.soinside.com 2019 - 2024. All rights reserved.