Drawing - Objects Example

Demonstrates drawing a circle on canvas with javascript objects

by rbrousla

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) {
    var x1 = Math.floor(this.centerX+this.radius*Math.cos(0));
    var y1 = Math.floor(this.centerY+this.radius*Math.sin(0));
    ctx.moveTo(x1,y1);
    for (var t = 0; t <= 2*Math.PI+.1; t+=0.1) {
     x1 = Math.floor(this.centerX+this.radius*Math.cos(t));
     y1 = Math.floor(this.centerY+this.radius*Math.sin(t));
     ctx.lineTo(x1,y1);
     ctx.stroke();
     }  
   }
}

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);   
}