JavaScript:Canvasアニメ課題

JavaScript

ボールを2つにする。
ball1, ball2というオブジェクトを追加した。

実行イメージ

index.html

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,user-scalable=yes">
    <script type="text/javascript" src="main.js"></script>
    <title>JavaScript:canvas壁に当たるとはね返る【ボール2つ】</title>
</head>
<body>
    <canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>

main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
let canvas = null// キャンバス
let g = null;       // 描画コンテキスト
 
// ボール1
let ball1 = {
    x: 100,
    y: 50,
    r: 30,
    vx: 5,
    vy: 3,
    color: "forestgreen",
};
 
// ボール2
let ball2 = {
    x: 200,
    y: 220,
    r: 50,
    vx: 4,
    vy: -5,
    color: "steelblue",
};
 
//let x, y, r;      // ●のx座標、y座標、半径
//let vx, vy;       // x方向の速度、y方向の速度
 
let balls = [];
 
function drawAnim(){
    // 背景をグレーに
    g.fillStyle = "#ddd";
    g.fillRect(0, 0, canvas.width, canvas.height);
    // ballを描画
    for(let ball of balls){
        g.beginPath();
        g.fillStyle = ball.color;   // 塗りつぶす色
        g.arc(ball.x, ball.y, ball.r, 0, Math.PI*2, false);
        g.fill();
        // ●の移動
        ball.x += ball.vx;
        ball.y += ball.vy;
        // 壁に当たったら跳ね返る(●のxy座標は中心点のため、半径を考慮)
        if(ball.x < 0+ball.r || ball.x > canvas.width-ball.r){
            ball.vx = -ball.vx;
        }
        if(ball.y < 0+ball.r || ball.y > canvas.height-ball.r){
            ball.vy = -ball.vy;
        }
    }
    // 再帰呼び出しでアニメーションさせる
    requestAnimationFrame(drawAnim);
}
 
window.addEventListener("load", ()=>{
    // キャンバスの初期設定
    canvas = document.getElementById("canvas");
    g = canvas.getContext("2d");
    // 描画するballの初期設定
    //ball.x = 100; ball.y = 50; ball.r = 30;
    //ball.vx = 5; ball.vy = 3;
    balls.push(ball1);
    balls.push(ball2);   
    // アニメーション開始
    drawAnim();
});

コメント