Fabric js copied objects are removed after zooming or rotating in the canvas

Discussão em 'Angular' iniciado por Victoria Erdődy, Outubro 31, 2024.

  1. I have a problem with copying and pasting objects in the canvas. The copy and paste functionalities itself work as expected, however, if I try to zoom in/out or rotate the canvas right after pasting the copied objects, the copied objects disappear from the canvas.

    I have this code structure:

    clipboard: fabric.Object;
    @HostListener('window:keydown.control.c', ['$event'])
    @HostListener('window:keydown.meta.c', ['$event'])
    copy(): void {
    if (this.drawService.canvas.getActiveObject()) {
    this.drawService.canvas.getActiveObject().clone((cloned: fabric.Object) => {
    this.clipboard = cloned;
    });
    }
    }

    @HostListener('window:keydown.control.v', ['$event'])
    @HostListener('window:keydown.meta.v', ['$event'])
    paste(): void {
    if (this.clipboard) {
    this.clipboard.clone((clonedObj: fabric.Object) => {
    this.drawService.canvas.discardActiveObject();
    clonedObj.set({
    left: clonedObj.left + 10,
    top: clonedObj.top + 10,
    evented: true,
    });
    if (clonedObj.type === 'activeSelection') {
    const activeSelection = clonedObj as fabric.ActiveSelection;
    activeSelection.canvas = this.drawService.canvas;
    activeSelection.forEachObject((obj: fabric.Object) => {
    this.drawService.canvas.add(obj);
    });
    clonedObj.setCoords();
    } else {
    this.drawService.canvas.add(clonedObj);
    }
    this.clipboard.top += 10;
    this.clipboard.left += 10;
    this.drawService.canvas.setActiveObject(clonedObj);
    this.drawService.canvas.renderAll();
    });
    }
    }


    The objects are copied and pasted correctly at the right position. But whenever, right after pasting the object I click on zoom in/out buttons, or rotation button, any object/s, that were previously copied are gone.

    However, if I add the the method for saving the canvas state at the end of the paste function:

    saveCanvasState(): void {
    this.internalCanvasState = this.drawService.canvas.toJSON(); // Capture the current canvas state
    console.log('Current Canvas State:', this.internalCanvasState); // Log for debugging
    }


    I can see all the objects - original and copied, even if I don´t see copied ones on the canvas.

    Can you suggest me some working solution where the copied objects stay on the canvas even if I zoom in/out, rotate the canvas?

    Continue reading...

Compartilhe esta Página