Drawing - Objects Example variables X,Y

Demonstrates drawing a circle on canvas with javascript objects

by Ron Eaglin

HTML

<button onclick="drawCircle();">Draw Circle</button>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

JavaScript

function Circle(x, y, aRadius) {
    this.centerX = x;
    this.centerY = y;
    this.radius = aRadius;
     
    // creates a method draw(passing context)
    this.draw = draw;
    function draw(ctx) {
    ctx.moveTo(this.X(0),this.Y(0));

    for (var t = 0; t <= 2*Math.PI+.1; t+=0.1) {
      ctx.lineTo(this.X(t),this.Y(t));
      ctx.stroke();
     }  
   }
    
    this.X = X;   
    function X(t) {
    return this.centerX+this.radius*Math.cos(t);
    }
    
    this.Y = Y;
    function Y(t) {
    return this.centerY+this.radius*Math.sin(t);    
    }
}

function drawCircle() {
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
    
  var myCircle = new Circle(c.width/2, c.height/2, 100);
  myCircle.draw(ctx);   
}