Canvas to DOM Background Image
Create a CSS spritesheet using the canvas to create a background image for a DOM button.
HTML
<!-- canvas width and hieght must be the exact dimensions of the 3 buttons side by side so that the resulting image doesn't have any whitespace -->
<canvas id="canvas" width="300" height="50"></canvas>
<a href="#" class="button">Play</a>
CSS
body {
margin: 0;
}
canvas {
border: 1px solid red;
}
.button {
width: 100px;
height: 50px;
line-height: 50px;
position: absolute;
left: 50px;
top: 100px;
color: #FFF;
text-decoration: none;
text-align: center;
font-size: 15px;
font-family: sans-serif;
background-repeat: no-repeat;
}
.button:hover {
background-position: -100px;
}
.button:active {
background-position: -200px;
}
JavaScript
(function() {
var ctx = canvas.getContext('2d');
/**
* A complex button background.
* @param {integer} x - X coordinate of the button.
* @param {integer} y - Y coordinate of the button.
* @param {integer} w - Width of the button.
* @param {integer} h - Height of the button.
* @param {object} colors - The colors of the button.
* @param {string} colors.background - The background color.
* @param {string} colors.top - Top particle color.
* @param {string} colors.bottom - Bottom particle color.
*/
function Button(x, y, w, h, colors) {
var halfHeight = h / 2;
ctx.save();
// draw the button
ctx.fillStyle = colors.background;
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.rect(x, y, w, h);
ctx.fill();
ctx.clip();
// light gradient
var grad = ctx.createLinearGradient(
x, y,
x, y + halfHeight
);
grad.addColorStop(0, 'rgb(221,181,155)');
grad.addColorStop(1, 'rgb(22,13,8)');
ctx.fillStyle = grad;
ctx.globalAlpha = 0.5;
ctx.fillRect(x, y, w, h);
// draw the top half of the button
ctx.fillStyle = colors.top;
// draw the top and bottom particles
for (var i = 0; i < h; i += halfHeight) {
ctx.fillStyle = (i === 0 ? colors.top : colors.bottom);
for (var j = 0; j < 50; j++) {
// get random values for particle
var partX = x + Math.random() * w;
var partY = y + i + Math.random() * halfHeight;
var width = Math.random() * 10;
var height = Math.random() * 10;
var rotation = Math.random() * 360;
var alpha = Math.random();
ctx.save();
// rotate the canvas by 'rotation'
ctx.translate(partX, partY);
ctx.rotate(rotation * Math.PI / 180);
ctx.translate(-partX, -partY);
// set alpha transparency to 'alpha'
...