Thursday, August 17, 2017

3. Circles

A Circle class stores center coordinates (x, y) and radius. It also has a draw method to draw the circle using the arc method.


The draw method requires optional fill color which is "blue" by default.


// 3. Circles

let canvas = document.querySelector("#myCanvas");
let ctx = canvas.getContext("2d");

class Circle {
  constructor(x, y, radius) {
    this.x = x;
    this.y = y;
    this.radius = radius;
  }
  draw(color="blue") {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
    ctx.fillStyle = color;
    ctx.fill();
  }
}

let circle1 = new Circle(100, 100, 40);
circle1.draw("red");

let circle2 = new Circle(200, 100, 42);
circle2.draw();

let circle3 = new Circle(100, 200, 44);
circle3.draw("green");

let circle4 = new Circle(200, 200, 46);
circle4.draw("purple");

Output:


No comments:

Post a Comment