LoginSignup
0
0

More than 1 year has passed since last update.

javascript classを使ってランダムな位置にランダムな円を描画する

Posted at

クラスはオブジェクトの設計書

クラス宣言内でクラスを宣言する際にはコンストラクターとメソッドで定義していきます。
コンストラクタとメソッドの書き方は以下の通りです。

class.js
class Member {
    //コンストラクタ
    constructor(fitstName, lastName) {
     this.firstName = firstName;
     this.lastNamr = lastName;
 }
    //メソッド
    getName() {
     return this.lastName + this.firstName;
 }
}

let m = new Member('太郎', '田中');
console.log(m.getName()); //結果:山田太郎

クラスの使い方が分かったので、canvasを使ってランダムな位置にランダムな円を描画してみました。

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ランダムな位置にランダムな円を描く</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
    <canvas id="canvas"  width="500" height="500"></canvas>
    <div class="canvas-txt"><h1>Sample</h1></div>
  
  <script type="text/javascript" src="main.js"></script>
</body>
</html>
main.js
class Circle {
  // コンストラクタ
  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; // 半径
  }
  // 描画メソッド
  draw() {
    g.beginPath();
    g.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
    g.stroke();
  }
}

var canvas = null; //キャンバス
var g = null; //コンテキスト

window.addEventListener("load", () => {
  canvas = document.getElementById("canvas");
  g = canvas.getContext("2d");

  for (let i = 0; i < 100; i++) {
    let arc = new Circle();
    arc.draw();
  }
});

参考:https://dianxnao.com/%E5%A1%97%E3%82%8A%E3%81%A4%E3%81%B6%E3%81%97%E5%86%86%E3%82%92%E3%82%AD%E3%83%A3%E3%83%B3%E3%83%90%E3%82%B9%E3%81%AB%E6%8F%8F%E3%81%8F%E3%82%AF%E3%83%A9%E3%82%B9%E3%82%92%E4%BD%9C%E3%81%A3%E3%81%A6/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0