I cannot for the life of me figure this out. I'm in the early stages of creating a web based timesheet. I'm trying to create a time grid where you can just click and drag to select the desired time frame. I have a mockup built, but for some reason the mappings are not matching up. If I click in a box, it has to be on the far left to select that box. I used "(ev._x) - (ev._x % 10)" to account for this, but it does not seem to do the trick. Any help would be much appreciated.
<pre lang="xml"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML 5 Test Page</title>
<script type="text/javascript">
function load() {
var canvas, context, tool, staticy, staticx, temp;
init();
function init() {
canvas = document.getElementById('c');
if (!canvas) {
alert('Error: I cannot find the canvas element!');
return;
}
if (!canvas.getContext) {
alert('Error: no canvas.getContext!');
return;
}
context = canvas.getContext('2d');
if (!context) {
alert('Error: failed to getContext!');
return;
}
tool = new tool_pencil();
canvas.addEventListener('mousedown', ev_canvas, false);
canvas.addEventListener('mousemove', ev_canvas, false);
canvas.addEventListener('mouseup', ev_canvas, false);
drawGrid();
}
function drawGrid() {
context.beginPath();
for (var i = 0.5; i < 501; i += 50) {
for (var x = 0.5; x <= 961; x += 10) {
context.moveTo(x, i);
context.lineTo(x, i + 40);
}
}
for (var y = 0.5; y < 500; y += 50) {
context.moveTo(0, y);
context.lineTo(961, y);
context.moveTo(0, y + 40);
context.lineTo(961, y + 40);
}
context.strokeStyle = "#000";
context.stroke();
}
function tool_pencil() {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
context.beginPath();
staticy = ev._y - (ev._y % 50);
staticx = (ev._x) - (ev._x % 10);
tool.started = true;
};
this.mousemove = function (ev) {
};
this.mouseup = function (ev) {
if (tool.started) {
context.fillStyle = "red";
context.fillRect(staticx, staticy, (ev._x - (ev._x % 10)) - staticx, 40);
context.stroke();
tool.started = false;
}
};
}
function ev_canvas(ev) {
if (ev.layerX || ev.layerX == 0) {
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) {
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}
var func = tool[ev.type];
if (func) {
func(ev);
}
}
}
</script>
</head>
<body onload="load()">
<canvas id="c" width="961" height="500"></canvas>
</body>
</html>
/edit - I've only tested on the most recent version of Chrome