0

我正在编写一个 Figma 插件来生成随机颜色并修改选择的填充。This works fine when the selection node has a fill. 但是当没有填充时,我在尝试应用时会出错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();
4

1 回答 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();
于 2020-03-18T12:52:41.607 回答