Skip to content

Instantly share code, notes, and snippets.

@mrgarita
Last active February 16, 2022 02:10
Show Gist options
  • Save mrgarita/363d052ac1e826031b4d4270640c81d7 to your computer and use it in GitHub Desktop.
Save mrgarita/363d052ac1e826031b4d4270640c81d7 to your computer and use it in GitHub Desktop.
JS:ランダムな位置にランダムな大きさの円を描く
/* ArcRandom.js : ランダムな位置に円を描くクラス*/
class ArcRandom{
// コンストラクタ
constructor(){
this.x = Math.floor(Math.random() * canvas.width); // x座標
this.y = Math.floor(Math.random() * canvas.height); // y座標
this.r = Math.floor(Math.random() * 50) + 1; // 半径
console.log("x: " + this.x + " y: " + this.y + " r=" + this.r);
}
// 描画メソッド
draw(){
g.beginPath();
g.arc(this.x, this.y, this.r, 0, Math.PI*2, false);
g.stroke();
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=yes">
<script src="ArcRandom.js" type="text/javascript"></script>
<title>キャンバスのランダムな位置に円を描くクラス</title>
<script type="text/javascript">
// キャンバス
var canvas = null;
var g = null;
window.addEventListener("load", function(){
// キャンバス取得
canvas = document.getElementById("canvas");
g = canvas.getContext("2d");
console.log("キャンバスのサイズ: " + canvas.width + " x " + canvas.height);
// クラスArcRandomを使ってランダムな位置に円を100個描く
for(let i=0; i<100; i++){
let arc = new ArcRandom();
arc.draw();
}
});
</script>
</head>
<body>
<h1>キャンバスのランダムな位置に円を描くクラス</h1>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment