Добавьте заливку к узлу, у которого нет пустого массива в плагине 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();
1 ответ
У меня есть решение (не обязательно правильное).
Похоже, мне нужно проверить, есть ли у исходного узла массив, а если нет, создать полный объект в массиве. Я думаю, что у меня была неправильная структура, когда я пытался это сделать раньше.
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();