向Figma插件中没有空数组的节点添加填充(TypeError:值没有属性)

问题描述 投票:0回答:1

我正在编写一个Figma插件来生成随机颜色并修改选择的填充。当选择节点具有填充时,此方法工作正常。但是,如果没有填充,尝试应用fills[0].color = newColor;时会出错。

在该节点上记录填充时,我得到[],我假设它是一个空数组。Figma节点可以具有多个填充,并且在分配值时要求格式为node.fills[1].color

那么如何为空数组的节点创建color分配?

import chroma from '../node_modules/chroma-js/chroma'
import clone from './clone'

for (const node of figma.currentPage.selection) {

  if ("fills" in node) {

    const fills = clone(node.fills);

    // Get a random colour from chroma-js.
    const random = chroma.random().gl();

    // Create an array that matches the fill structure (rgb represented as 0 to 1)
    const newColor = {r: random[0], g: random[1], b: random[2]};

    // Only change the first fill
    fills[0].color = newColor;

    // Replace the fills on the node.
    node.fills = fills;
  }
}

// Make sure to close the plugin when you're done. Otherwise the plugin will
// keep running, which shows the cancel button at the bottom of the screen.
figma.closePlugin();
javascript arrays typescript fill figma
1个回答
0
投票

我有一个解决方案(不一定正确)。

看来我需要检查原始节点是否具有数组,如果没有,请在数组中创建一个完整的对象。我认为以前尝试过这种结构时,结构是错误的。

import chroma from '../node_modules/chroma-js/chroma'
import clone from './clone'

for (const node of figma.currentPage.selection) {

  if ("fills" in node) {

    let fills;

    // Check to see if the initial node has an array and if it's empty
    if (Array.isArray(node.fills) && node.fills.length) {

      // Get the current fills in order to clone and modify them      
      fills = clone(node.fills);

    } else {

      // Construct the fill object manually
      fills = [{type: "SOLID", visible: true, opacity: 1, blendMode: "NORMAL", color: {}}]
    }

      // Get a random colour from chroma-js.
      const random = chroma.random().gl();

      // Create an array that matches the fill structure (rgb represented as 0 to 1)
      const newColor = {r: random[0], g: random[1], b: random[2]};

      // Only change the first fill
      fills[0].color = newColor;

      // Replace the fills on the node.
      node.fills = fills;

    // }
  }
}

// Make sure to close the plugin when you're done. Otherwise the plugin will
// keep running, which shows the cancel button at the bottom of the screen.
figma.closePlugin();
© www.soinside.com 2019 - 2024. All rights reserved.