木曜日, 1月 08, 2026

JavaScriptでAI遊び 83 
選択図形のランダムパターン(四角)

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

/*
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 w = 5 + Math.random() * 30;
var h = 5 + Math.random() * 30;

var rect2 = doc.pathItems.rectangle(
y, x, w, h
);
rect2.filled = true;
rect2.stroked = false;
rect2.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("ランダムパターンのベース生成が完了しました。");

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