I am writing a Figma plugin to generate a random colour and modify the fill of a selection.
This works fine when the selection node has a fill. But when there is no fill I get an error when trying to apply fills[0].color = newColor;
.
When logging the fill on that node I get []
which I'm assuming is an empty array.
Figma nodes can have multiple fills and requires the format node.fills[1].color
when assigning values.
So how can I create a color
assignment for a node where there is an empty array?
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();