Shapes and Canvas Basics
HTML
<canvas class="redborder" id="canv1" width="800" height="600"></canvas>
<br/>
<br/>
<h3>Drawing grid lines</h3>
<canvas class="redborder" id="canv2" width="800" height="400"></canvas>
<div id="results" />
CSS
body {
margin:10px;
}
.pass {
color:green;
}
.fail {
color:red;
text-decoration:line-through;
}
.redborder {
border: red 2px solid;
}
JavaScript
$(document).ready(function () {
function assert(value, desc) {
var res = $("#results");
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
li.appendChild(document.createTextNode(desc));
res.append(li);
}
function drawGridLines(canvasElem, spacing, color, lineWidth) {
// get canvas width and height
var width = canvasElem.width;
var height = canvasElem.height;
var context = canvasElem.getContext("2d");
// draw horizontal lines
for (var i = spacing; i < height; i = i + spacing) {
drawLine(canvasElem, 0, i, width, i, color, lineWidth);
}
// draw vertical lines
for (var j = spacing; j < width; j = j + spacing) {
drawLine(canvasElem, j, 0, j, height, color, lineWidth);
}
}
function drawLine(canvasElem, x1, y1, x2, y2, color, lineWidth) {
var ctx = canvasElem.getContext("2d");
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = color;
ctx.lineWidth = lineWidth;
ctx.stroke();
}
var canvas = $("#canv1");
var ctx = canvas[0].getContext("2d");
// render a rectangle
// in 2d context, the x and y coords are 0 0 at top left corner of canvas
// x increases on the right and y increases downwards
ctx.fillStyle = 'Red';
ctx.fillRect(10, 10, 200, 100);
// render an arc
// arc takes x, y, radius, startangle, endangle and anticlockwise
// to render full circle pass 0 and 2*Math.PI as the values for start and end angle
ctx.arc(100, 200, 50, 0, 2 * Math.PI, false);
ctx.fillStyle = "Green";
ctx.fill();
// call to beginPath is required to keep each shape distinct
// drawing a semi circle
ctx.beginPath();
ctx.arc(100, 310, 50, 0, Math.PI, true);
ctx.fillStyle = "Green";
ctx.fill();
// drawing a line
ctx.beginPath();
...