Why Fabric canvas modal initial rendering Error

18 Views Asked by At
import React, { useEffect, useRef, useState } from 'react';
import { Box, Modal } from "@mui/material";
import { fabric } from 'fabric';

interface EditModalProps {
    onClose: () => void;
    open: boolean;
    imageUrl?: string;
    segmentImageUrls?: string[];
}

const EditModal = ({ onClose, open, imageUrl, segmentImageUrls = [] }: EditModalProps) => {
    const canvasRef = useRef<HTMLCanvasElement | null>(null);

    useEffect(() => {
        if (!open || !imageUrl || !canvasRef.current) return;

        const canvas = new fabric.Canvas(canvasRef.current);

        const imagePromises = [
            new Promise<fabric.Image>((resolve) => fabric.Image.fromURL(imageUrl, (img) => {
                img.set({
                    selectable: false,
                });
                resolve(img);
            })),
            ...segmentImageUrls.map(url => new Promise<fabric.Image>((resolve) => fabric.Image.fromURL(url, (img) => {
                img.set({
                    selectable: false,
                });
                resolve(img);
            }))),
        ];

        Promise.all(imagePromises).then(images => {
            const [mainImage, ...segmentImages] = images;

            canvas.setWidth(mainImage.width as number);
            canvas.setHeight(mainImage.height as number);

            canvas.add(mainImage);
            canvas.sendToBack(mainImage);

            segmentImages.forEach(img => {
                canvas.add(img);
            });

            canvas.renderAll();
        });

        canvas.isDrawingMode = true;
        canvas.freeDrawingBrush = new fabric.PencilBrush(canvas);
        canvas.freeDrawingBrush.color = "green";
        canvas.freeDrawingBrush.width = 5;

        return () => {
            canvas.dispose();
        };
    }, [open, imageUrl, segmentImageUrls]);

    return (
        <Modal open={open} onClose={onClose}>
            <Box 
                sx={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: '100%', height: '100%', bgcolor: 'background.paper', border: '1px solid #000', boxShadow: 24, pt: 2, px: 4, pb: 3, overflow: 'auto' }}>
                <div>
                    <button onClick={onClose}>Close</button>
                </div>
                <div>
                    <canvas ref={canvasRef} />
                </div>
            </Box>
        </Modal>
    );
};

export default EditModal;

Upon initial entry to EditModal, the screen is blank. However, if you save your code in vscode, you will see the corresponding canvas screen.

The order in which EditModal opens after pressing a button in an existing modal.

enter image description here

first, [수정하기] button click!

enter image description here

0

There are 0 best solutions below