月曜日, 1月 05, 2026

JavaScriptでAI遊び 82 
選択図形のランダムパターン(円)

選択した図形内にパターンを作成〜の円編です。
作業するレイヤーの上に非表示のレイヤーが有るとエラーが出ます。

/*
Illustrator Script
選択した矩形内にランダム円パターンを生成
*/

if (app.documents.length === 0) {
alert("ドキュメントがありません。");
exit();
}

var doc = app.activeDocument;

// --- 選択チェック ---
if (doc.selection.length !== 1 || !(doc.selection[0]
instanceof PathItem)) {
alert("矩形を1つだけ選択してください。");
exit();
}

var rect = doc.selection[0];

// --- 図形チェック(4点+クローズパス) ---
if (!rect.closed || rect.pathPoints.length !== 4) {
alert("選択対象は矩形ではありません。");
exit();
}

// --- 座標の取得 ---
var left = rect.geometricBounds[0]; // 左
var top = rect.geometricBounds[1]; // 上
var right = rect.geometricBounds[2]; // 右
var bottom = rect.geometricBounds[3]; // 下
var width = right - left;
var height = top - bottom;

// --- パターンの設定 ---
var count = 100; // 生成する要素数

// ------- ▼▼ パターン生成ループ
for (var i = 0; i < count; i++) {

// ランダム座標(矩形内)
var x = left + Math.random() * width;
var y = top - Math.random() * height;

// -----------------------------------------
// ランダム円
var r = 5 + Math.random() * 15;

var shape = doc.pathItems.ellipse(
y + r, // 上
x - r, // 左
r * 2, // 幅
r * 2 // 高さ
);

shape.filled = true;
shape.stroked = false;
shape.fillColor = randomRGB();
// -----------------------------------------
}
// ------- ▲▲ パターン生成ループ

// --- RGBランダム色 ---
function randomRGB() {
var c = new RGBColor();
c.red = Math.random() * 255;
c.green = Math.random() * 255;
c.blue = Math.random() * 255;
return c;
}

alert("ランダムパターンのベース生成が完了しました。");

実行例です。内部へ完全に治まるわけではありません。