如何移动在nextjs useState中创建的fabricjs对象?

yx2lnoni  于 2024-01-07  发布在  其他
关注(0)|答案(1)|浏览(108)

当我在useEffect()中创建一个织物画布时,它不允许我移动添加的图像,但如果我在其他地方创建它(受useState错误问题的影响),它确实允许我正常移动。代码不工作,但正是我所需要的:

export default function Home(){
 const [canvas, setCanvas] = useState();

 useEffect(() => {
  setCanvas(new fabric.Canvas('canvas', selectable: true, renderOnAddRemove: false}));
 }, []);

 const addImage = () => {
  canvas.add(new fabric.Image("/myImage.png").renderAll();
 }

 return(
  <>
   <canvas id="canvas" />
   <button onClick(addImage)>Add Image </button>
  </>
 )
}

字符串

mbjcgjjk

mbjcgjjk1#

我遇到了这个问题,一直试图修复它,但没有运气。不是直接修复,但我建议使用https://www.npmjs.com/package/fabricjs-react,所以在安装它之后(npm install --保存fabricjs-react fabric),你的代码将看起来像这样:

'use client'
import React from 'react';
import { FabricJSCanvas, useFabricJSEditor } from 'fabricjs-react';

const SimpleCanvas = () => {
  const { editor, onReady } = useFabricJSEditor();

  const addImage = () => {
    if (editor) {
      const imageUrl = '/myImage.jpg'; // Path to your image
      fabric.Image.fromURL(imageUrl, (img) => {
        // Add customization to the image here if necessary
        img.set({
          left: 100,
          top: 100,
          angle: 0,
          selectable: true
        });

        // Add the image to the Fabric.js canvas
        editor.canvas.add(img);
      });
    }
  };

  return (
    <div>
      <FabricJSCanvas onReady={onReady} />
      <button onClick={addImage}>Add Image</button>
    </div>
  );
};

export default SimpleCanvas;

字符串
希望对你有帮助。

相关问题