Canvas based button
Code for a simple canvas based button.
HTML
<canvas id="canvas" width="200" height="200">
JavaScript
(function() {
var ctx = canvas.getContext('2d');
ctx.font = '15px sans-serif';
// mouse event variables
var mousePosition = {
x: 0,
y: 0
};
var mousePressed = false;
/**
* Track the user's mouse position on mouse move.
* @param {Event} event
*/
canvas.addEventListener('mousemove', function(event) {
mousePosition.x = event.offsetX || event.layerX;
mousePosition.y = event.offsetY || event.layerY;
});
/**
* Track the user's clicks.
* @param {Event} event
*/
canvas.addEventListener('mousedown', function(event) {
mousePressed = true;
});
canvas.addEventListener('mouseup', function(event) {
mousePressed = false;
});
/**
* A button with hover and active states.
* @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 {string} text - Text on the button.
* @param {object} colors - Default, hover, and active colors.
*
* @param {object} colors.default - Default colors.
* @param {string} colors.default.top - Top default button color.
* @param {string} colors.default.bottom - Bottom default button color.
*
* @param {object} colors.hover - Hover colors.
* @param {string} colors.hover.top - Top hover button color.
* @param {string} colors.hover.bottom - Bottom hover button color.
*
* @param {object} colors.active - Active colors.
* @param {string} colors.active.top - Top active button color.
* @param {string} colors.active.bottom - Bottom active button color.
*
* @param {function} clickCB - The funciton to call when the button is clicked.
*/
function Button(x, y, w, h, text, colors, clickCB) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
...