Fake Buttons on Canvas
by mkennedy
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
Mouse Click: <span id="status"></span><br/>
Mouse Postion: <span id="pos"></span><br/>
<button id="stop">Stop adding buttons</button><br/>
<canvas width="500" height="400" style="background-color: lightblue;"></canvas>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</body>
</html>
JavaScript
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
// Drawing.js
var canvasApp = canvasApp || {};
canvasApp.drawing = canvasApp.drawing || {};
/* roundedRect(ctx,x,y,width,height,radius,fill,stroke)
Arguments: ctx - the context to be used to draw with.
x,y - the top left corner
width - how wide the rectangle
height - how high the rectangle
radius - the radius of the corner
fill - true if the rectangle should be filled
stroke - true if the rectangle should be stroked */
canvasApp.drawing.roundedRect = function(ctx, x, y, width, height, radius, fill, stroke) {
ctx.save(); // save the context so we don't mess up others
ctx.beginPath();
// draw top and top right corner
ctx.moveTo(x + radius, y);
ctx.arcTo(x + width, y, x + width, y + radius, radius);
// draw right side and bottom right corner
ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius);
// draw bottom and bottom left corner
ctx.arcTo(x, y + height, x, y + height - radius, radius);
// draw left and top left corner
ctx.arcTo(x, y, x + radius, y, radius);
if (fill) {
ctx.fill();
}
if (stroke) {
ctx.stroke();
}
ctx.restore(); // restore context to what it was on entry
};
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
// interaction.js
canvasApp.interaction = canvasApp.interaction || {};
canvasApp.interaction.relMouseCoords = function (element, event) {
if (event.offsetX !== undefined && event.offsetY !== undefined) {
return {
x: event.offsetX,
y: event.offsetY,
pageX: event.pageX,
pageY: event.pageY
};
}
var totalOffsetX = 0;
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var currentElement = element;
...