[Vuejs]-How to create fabric canvas dynamically when opening a new window

0👍

I solve this problem
Passing the element without passing the id solved it
I don’t know why, let me know if you know

const openCanvasPopup = () => {
  const newWindow = window.open("", "_blank");
  if (newWindow) {
    const newCanvasElement = document.createElement('canvas');
    newWindow.document.body.appendChild(newCanvasElement);

    const newCanvas = new fabric.Canvas(newCanvasElement)

    newCanvas.loadFromJSON(jsonData.value, () => {
    });
  }
}

-1👍

Your code seems mostly correct, but the issue might be related to timing or scope. Here are a few things to consider:

  1. Ensure Fabric.js is Loaded:
    Make sure you have properly loaded the Fabric.js library in the new window’s HTML. You should include the script tag for Fabric.js in the <head> of the new window’s document.

  2. Wait for Window to Load:
    Ensure that you’re not trying to manipulate the DOM before the new window’s document has fully loaded. You can use the load event to ensure that the document is ready before performing any DOM manipulations.

Here’s an updated version of your code that waits for the new window to load before adding the canvas:

javascript
const openCanvasPopup = () => {
  const newWindow = window.open("", "_blank");

  if (newWindow) {
    newWindow.document.addEventListener('DOMContentLoaded', () => {
      const newCanvasElement = document.createElement('canvas');
      newCanvasElement.id = "canvasPopup";
      newCanvasElement.width = newWindow.innerWidth;
      newCanvasElement.height = newWindow.innerHeight;
      newWindow.document.body.appendChild(newCanvasElement);

      const newCanvas = new fabric.Canvas('canvasPopup');
      newCanvas.loadFromJSON(jsonData.value, () => {
        newCanvas.renderAll();
      });
    });
  }
};

By adding an event listener for the DOMContentLoaded event on the new window’s document, you ensure that the document is fully loaded before attempting to manipulate the DOM.

If you’re still experiencing issues, consider checking your browser’s console for any error messages that might provide more insight into the problem.

Leave a comment