GASで簡単!図形の挿入・操作・描画・削除・取得の完全ガイド


図形の挿入
GASを使ってGoogleスライドに簡単に図形を挿入できます。次のコードを見てみよう。
function insertShape() {
const presentation = SlidesApp.getActivePresentation();
const slide = presentation.getSlides()[0];
slide.insertShape(SlidesApp.ShapeType.RECTANGLE, 50, 50, 300, 150);
}
– SlidesApp.getActivePresentation() で現在編集中のプレゼンテーションを取得する。
– getSlides()[0] で最初のスライドを指定する。
– insertShape() で指定した形(この場合は長方形)をスライドに挿入している。

図形の操作
挿入した図形の色や位置を変更することも可能だ。操作する例を見ていこう。
function manipulateShape() {
const presentation = SlidesApp.getActivePresentation();
const slide = presentation.getSlides()[0];
const shape = slide.insertShape(SlidesApp.ShapeType.RECTANGLE, 50, 50, 200, 100);
shape.getFill().setSolidFill('#FF0000');
shape.setLeft(100);
shape.setTop(100);
}
– getFill().setSolidFill() で図形の塗りつぶし色を設定する。
– setLeft() と setTop() で図形の位置を変更する。

図形の描画
GASで図形を描画する際に、それぞれのプロパティを細かく調整できる。
function drawShapeWithDetails() {
const presentation = SlidesApp.getActivePresentation();
const slide = presentation.getSlides()[0];
const shape = slide.insertShape(SlidesApp.ShapeType.ELLIPSE, 20, 20, 150, 150);
shape.getBorder().setWeight(3);
shape.getBorder().setSolidFill('#0000FF');
}
– getBorder().setWeight() で輪郭の太さを指定できる。
– setSolidFill() を使って輪郭の色も設定可能だ。

図形の削除
挿入した図形が不要になった場合、GASを使って削除することが可能だ。
function deleteShape() {
const presentation = SlidesApp.getActivePresentation();
const slide = presentation.getSlides()[0];
const shapes = slide.getShapes();
shapes[0].remove(); // 最初の図形を削除する
}
– getShapes() でスライド上のすべての図形を取得し、remove() を使って削除する。

図形の取得
すでにある図形に対して操作をしたい場合は、図形を取得する方法を学ぼう。
function getShapeAndLogDetails() {
const presentation = SlidesApp.getActivePresentation();
const slide = presentation.getSlides()[0];
const shapes = slide.getShapes();
const shapeDetails = shapes[0].getBounds();
Logger.log('Width: ' + shapeDetails.getWidth());
Logger.log('Height: ' + shapeDetails.getHeight());
}
– getBounds() でその図形の寸法を取得でき、プロパティとして getWidth() や getHeight() が使用可能だ。

練習問題
以下の問題に取り組んで、GASでの図形処理を確認してみよう。
1. Googleスライドに黄色の円を挿入し、位置を(200, 200)に設定してください。
2. 上記の円に青色の輪郭をつけてみましょう。
3. 作成した円を削除してください。
解答と解説
function practiceShapes() {
const presentation = SlidesApp.getActivePresentation();
const slide = presentation.getSlides()[0];
// 問題1: 黄色の円を挿入
const yellowCircle = slide.insertShape(SlidesApp.ShapeType.ELLIPSE, 200, 200, 100, 100);
yellowCircle.getFill().setSolidFill('#FFFF00');
// 問題2: 青色の輪郭を追加
yellowCircle.getBorder().setWeight(2);
yellowCircle.getBorder().setSolidFill('#0000FF');
// 問題3: 円を削除
yellowCircle.remove();
}
– insertShape() で円を挿入し、色を設定。
– getBorder().setSolidFill() で輪郭の色を青に設定。
– 最後に remove() メソッドで円を削除。
