Created
November 23, 2024 04:47
-
-
Save hiloki/e86e2dc0d188749087bbe8095c56fd48 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const API_URL = "https://dog.ceo/api/breeds/image/random"; // 犬画像API | |
// 選択された要素を取得 | |
const selection = figma.currentPage.selection; | |
if (selection.length === 0) { | |
figma.notify("少なくとも1つのRectangleを選択してください。"); | |
} else { | |
const processNode = (node, delay) => { | |
if (node.type === "RECTANGLE") { | |
// 1秒の遅延を設定 | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
// 犬の画像を取得 | |
fetch(API_URL) | |
.then((response) => { | |
if (!response.ok) | |
throw new Error("APIからのレスポンスが不正です"); | |
return response.json(); // JSON形式でレスポンスを取得 | |
}) | |
.then((data) => { | |
if (!data.message || !data.message.endsWith(".jpg")) { | |
throw new Error("有効な画像URLが取得できませんでした"); | |
} | |
const imageUrl = data.message; // 画像URLを取得 | |
// 画像データを取得して設定 | |
return fetch(imageUrl) | |
.then((imageResponse) => { | |
if (!imageResponse.ok) | |
throw new Error("画像の取得に失敗しました"); | |
return imageResponse.arrayBuffer(); | |
}) | |
.then((arrayBuffer) => { | |
const uint8Array = new Uint8Array(arrayBuffer); | |
const image = figma.createImage(uint8Array); | |
// Rectangleの塗りつぶしを設定 | |
node.fills = [ | |
{ | |
type: "IMAGE", | |
scaleMode: "FILL", | |
imageHash: image.hash, | |
}, | |
]; | |
resolve(); | |
}); | |
}) | |
.catch((error) => { | |
console.error(`エラーが発生しました (${node.name}):`, error); | |
resolve(); // エラーがあっても次に進む | |
}); | |
}, delay); | |
}); | |
} else { | |
console.warn(`選択された要素 (${node.name}) はRectangleではありません。`); | |
return Promise.resolve(); // 非Rectangle要素は無視 | |
} | |
}; | |
// 選択されたRectangleを順次処理 | |
const promises = selection.map((node, index) => | |
processNode(node, index * 1000) | |
); | |
// 全ての処理が完了したら通知を表示 | |
Promise.all(promises).then(() => { | |
figma.notify("選択されたRectangleに犬の画像を設定しました!"); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment