このページでは,配列とif文を使って,複数の緑色の円の中に,緑色のひし形を1つ,赤色の円を1つ配置する方法を学びます。

以下のチュートリアルが終了した状態から始めます。

2. 円をランダムな位置に並べてみよう

1. ランダムな位置に5つの円を描く

前のページでは,次のコードを使って,3行×3列の9か所からランダムに5か所を選び,緑色の円を描画しました。

const xloc = [-300, 0, 300];
const yloc = [-150, 0, 150];
const setSize = 5;

const positionList = [0, 1, 2, 3, 4, 5, 6, 7, 8];
const sampleList = this.random.shuffle(positionList);

for (let i = 0; i < setSize; i++) {
    const position = sampleList[i];
    const xp = position % 3;
    const yp = Math.floor(position / 3);

    this.options.content.push({
        type: 'circle',
        left: xloc[xp], top: yloc[yp], angle: 0,
        width: 100,
        fill: null,
        stroke: 'green', strokeWidth: 5
    });
}

実行すると,3行×3列のランダムな位置に5つの円が表示されます。

image.png

2. 1つだけひし形を呈示する

次に,5つの刺激のうち,1つだけをひし形に変更します。

2.1. ひし形を作る

ここでは,正方形であるrectを45度回転させて,ひし形を作ります。

ひし形を描画するときは,次のように指定します。

type: 'rect',
angle: 45

円を描画するときは,次のように指定します。

type: 'circle',
angle: 0

今回は,for文の1回目にひし形を描画し,2回目から5回目までは円を描画します。

図形の種類と角度を保存するために,次の変数を使用します。