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



我正在编写一个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();

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

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

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();

最新更新