index.html
<!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>Canvas:オブジェクトでボールを100個生成して動かす</title>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>
main.js
// main.js
let canvas = null; // キャンバス
let g = null; // 描画コンテキスト
let balls = []; // ボール格納用
// min~max間の整数乱数を生成するアロー関数式
const randInt = (min, max)=>{
return Math.floor(Math.random() * (max+1-min)+min);
};
// ランダムカラー文字列を生成して返すアロー関数式
const getRandomColor = ()=>{
const get256 = ()=>{ return Math.floor(Math.random()*256); }; // 0 ~ 255を返す
let [r, g, b] = [get256(), get256(), get256()]; // ランダムでRGBカラーを設定
let color = `rgb(${r}, ${g}, ${b})`; // 文字列生成 'rgb(XX, XXX, XXX)'
return color;
};
// ball配列を使ってアニメーション処理を行う
const drawAnim = ()=>{
// 背景をグレーに塗りつぶし
g.fillStyle = "#eee";
g.fillRect(0, 0, canvas.width, canvas.height);
// ボールの描画・移動・壁との当たり判定
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");
// ボールを100個生成
for(let i=0; i<100; i++){
// ボール生成(半径・X方向の速度・Y方向の速度・色)
let ballObject = {
r: randInt(10, 50),
vx: randInt(1, 5),
vy: randInt(1, 5),
color: getRandomColor(),
setPos: function(){
let r = this.r;
this.x = randInt(r, canvas.width - r);
this.y = randInt(r, canvas.height - r);
}
};
// 半径からXY座標を設定
ballObject.setPos();
// 配列に代入
console.log({ballObject});
balls.push(ballObject);
}
// アニメーション開始
drawAnim();
});
コメント