Skip to main content
Question

Trying to understand how createImageAsync() works


Hi there,

If I understand this correctly, the global object “createImageAsync()” must be used if you want to add an image from a URL site.

figma.com

I tried to run code with this object, but I kept getting an error saying I needed to specify the URL in the allowedDomains in the manifest json file. So I added the URL in the manifest, but now I get another error saying it’s unable to fetch the image. Is this because of admin permission error?

Please let me know what you think. In the meantime, I’ll share my code below.

code.ts

figma.showUI(__html__);

async function createImageNode(url: string) {
    try {
        const image = await figma.createImageAsync(url);
        const imageHash = image.hash;

        const imageNode = figma.createRectangle();

        const { width, height } = await image.getSizeAsync();
        imageNode.resize(width, height);

        // Render the image by filling the rectangle.
        imageNode.fills = [
            {
                type: 'IMAGE',
                imageHash: imageHash,
                scaleMode: 'FILL'
            }
        ];

        // Adjust the position of the image node as needed
        imageNode.x = 100;
        imageNode.y = 100;

        figma.currentPage.appendChild(imageNode);
    } catch (error) {
        console.error('Error creating image:', error);
    } finally {
        figma.closePlugin();
    }
}

figma.ui.onmessage = (msg) => {
    if (msg.type === 'create-image') {
        const imageUrl = msg.url || 'https://via.placeholder.com/ffffff';
        createImageNode(imageUrl);
    }
};

manifest.json:

{
  "name": "image-import",
  "id": "1313731137931504902",
  "api": "1.0.0",
  "main": "code.js",
  "capabilities": [],
  "enableProposedApi": false,
  "editorType": [
    "figma"
  ],
  "ui": "ui.html",
  "networkAccess": {
    "allowedDomains": [
      "https://via.placeholder.com/"
    ]
  }
}

0 replies

Be the first to reply!

Reply


Cookie policy

We use cookies to enhance and personalize your experience. If you accept you agree to our full cookie policy. Learn more about our cookies.

 
Cookie settings