JavaScript
var faces = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 1, 0, 1, 1, 0, 1],
[1, 0, 1, 1, 1, 1, 1, 0, 1],
[1, 1, 1, 1, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1]
];
// Main method
(function() {
var rows = 3;
var columns = 3;
var canvasList = document.querySelectorAll('canvas[id^="die-"]');
for (var i = 0; i < canvasList.length; i++) {
drawDie(canvasList[i].getContext('2d'), i, faces, rows, columns);
}
}());
function drawDie(context, count, faces, rows, columns) {
var width = context.canvas.clientWidth;
var height = context.canvas.clientHeight;
drawBackground(context, width, height);
if (count > 0) {
drawPips(context, width, height, count, faces, rows, columns);
}
}
function drawBackground(context, width, height) {
context.fillStyle = '#FFFFFF';
context.strokeStyle = '#FF0000';
roundRect(context, 0, 0, width, height, width * 0.2, true, true);
}
function drawPips(context, width, height, count, faces, rows, columns) {
var x = measure(width, columns, 0.05);
var y = measure(height, rows, 0.05);
var radius = Math.min(x.off, y.off) * 0.33;
var hue = randRange(0, 360);
var fill = hslToHex(hue, 0.85, 0.55);
var stroke = hslToHex(hue, 0.85, 0.33);
var pipMap = faces[count];
var index = 0;
for (var yPos = y.start; yPos < y.avail; yPos += y.off) {
for (var xPos = x.start; xPos < x.avail; xPos += x.off) {
if (pipMap[index++] === 1) {
drawPip(context, xPos, yPos, radius, fill, stroke);
}
}
}
}
function drawPip(context, x, y, radius, fill, stroke) {
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.fillStyle = fill;
context.fill();
context.lineWidth = 2;
context.strokeStyle = stroke;
context.stroke();
}
// http://stackoverflow.com/a/3368118/1762224
function roundRect(ctx, x, y, width,...