HTML5 Canvas - Circle Calculations
Three filled triangles, two unfilled (stroke) triangles.
by BenjaminRay
HTML
<canvas id="myCanvas" width="800" height="600" style="border: 1px solid #dddddd;">
<p>Default content to be overwritten.</p>
</canvas>
JavaScript
// This is for testing circle trigonometry. To actually draw a circle, you can just use the arc()
// function. That's not what this is about.
function draw() {
// canvas with id="myCanvas"
var canvas = document.getElementById('myCanvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath(); // note usage below
// Set size of points to draw
var psize = 1; // If > 1, will expand down & to the right from coordinate
// Value by which to increment angle (radians) between points
var angleIncrement = 0.1;
// Set radius
var radius = 50;
// Set origin
var origin_x = 300;
var origin_y = 300;
// Draw center point (origin)
ctx.fillStyle = "#0000ff";
ctx.strokeStyle = "#0000ff";
ctx.arc(origin_x, origin_y, 2, 0, 2*Math.PI);
ctx.stroke(); // Outline
ctx.fill(); // Fill
// Draw points around the circle by incrementing angle
for (angle=0; angle < 2*Math.PI; angle+=angleIncrement) {
// Draw each point based on x/y origin, radius*cos(angle) for x and radius*sin(angle) for y
ctx.fillRect(origin_x + radius * Math.cos(angle), origin_y + radius * Math.sin(angle), psize, psize);
}
// triangle 1, at left
ctx.beginPath(); // note: w/o this, color does not work as expected
ctx.fillStyle = "#F9A520";
ctx.moveTo(0, 0); // start at top left corner of canvas
ctx.lineTo(200, 0); // go 200px to right (x), straight line from 0 to 0
ctx.lineTo(100, 200); // go to horizontal 100 (x) and vertical 200 (y)
ctx.fill(); // connect and fill
ctx.beginPath(); // note: w/o this, color does not work as expected
// triangle 2, top center
ctx.moveTo(300, 0); // pick up "pen," reposition at 300 (horiz), 0 (vert)
ctx.lineTo(300, 200); // draw straight down (from 300,0) to 200px
ctx.lineTo(500, 100); // draw up toward right (100 half of 200)
//ctx.fill(); // connect and fill
// triangle 3, bottom center
...