HTML5 CANVAS Sandbox
by JeffC
HTML
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes -->
<body onload="draw();">
<canvas id="canvas"></canvas>
</body>
JavaScript
//arc(x, y, radius, startAngle (radians), endAngle (radians), anticlockwise);
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
var height = 150;
var width = 150;
var r = 10;
canvas.height = height;
canvas.width = width;
ctx.save();
createBorder(ctx, width, height);
// draw stuff
ctx.strokeStyle = "#F00";
ctx.lineWidth = 3;
for (var i = r / 2; i <= width - r / 2; i += r / 2) {
ctx.beginPath();
var x = getRandomIntInclusive(0, width);
var y = getRandomIntInclusive(0, height);
drawCircle(ctx, x, y, r);
ctx.closePath();
ctx.stroke();
}
}
}
function drawCircle(ctx, x, y, r) {
ctx.arc(x, y, r, 0, Math.PI * 2, true);
}
// Returns a random integer between min (included) and max (included)
// Using Math.round() will give you a non-uniform distribution!
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function createBorder(ctx, width, height) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, height);
ctx.lineTo(width, height);
ctx.lineTo(width, 0);
ctx.lineTo(0, 0);
ctx.lineWidth = 3;
ctx.stroke();
ctx.restore();
}