I've been working on touch events and have some code working quite nicely, until the canvas doesn't start at the top left corner. As soon as I add anything before it, the reported event is offset by the position of the canvas.
I determine this by drawing a circle around where the touch was. The circle is always offset by the offset of the canvas from top left corner of the screen.
Looking at the event for on touch start, I can see that there is a pageY available (within chrome, using usb debugging). But when I google it, it seems that it's not a part of the standard and there appears to be some contention that it may be depreciated (though I cannot find out one way or the other).
So my question is what is the best cross browser method to deal with this (main concerns are safari and chrome, ie webkit, firefox is a nice to have)?
The same issue occurs for mouse events, for which I created a JSFiddle of the problem. However I' not sure if the same attributes are available for mouse events and touch events.
I should note, I am aware that I can hard code the offset and the problem is solved, however I'm looking for a solution that uses the information at hand without requiring any hard wired code specific to my html.
To recreate the JSFiddle, the HTML, CSS and Javascript are as follows:
<div class="title"></div>
<div class="container">
<canvas id="myCanvas"></canvas>
</div>
CSS:
body {
background-color: #ff0000;
margin: 0px;
}
canvas {
display:block;
position:absolute;
width:100%;
height:100%;
background-color:#000;
}
.title {
position:absolute;
top:0px;
left:0px;
width: 100%;
height: 40px;
background-color: #888;
}
.container {
width:auto;
text-align:center;
background-color:#777;
width:100%;
position:absolute;
top:40px;
left:0px;
bottom:0px;
}
Javascript:
var onMouseDown = function(e) {
draw(document.getElementById('myCanvas').getContext('2d'), e.clientX, e.clientY);
}
$(function () {
document.getElementById('myCanvas').addEventListener('mousedown', onMouseDown, false);
});
function draw(ctx, x, y) {
ctx.canvas.width = ctx.canvas.offsetWidth;
ctx.canvas.height = ctx.canvas.offsetHeight;
var radius = 50;
var lineWidth = 15;
var r = 255;
var g = 75;
var b = 75;
var a75 = 0.05;
var adj = Math.abs(lineWidth / 2);
rad = radius + adj;
var stop1 = (rad - lineWidth) / rad;
var stop2 = 0;
var stop3 = stop1 + (1 - stop1) / 2;
var stop4 = 0;
var stop5 = 1;
stop2 = stop3 - (stop3 - stop1) / 2;
stop4 = stop3 + (stop5 - stop3) / 2;
var radgrad = ctx.createRadialGradient(x, y, 0, x, y, rad);
radgrad.addColorStop(stop1, 'rgba(' + r + ',' + g + ',' + b + ', 0)');
radgrad.addColorStop(stop2, 'rgba(' + r + ',' + g + ',' + b + ', .4)');
radgrad.addColorStop(stop3, 'rgba(' + r + ',' + g + ',' + b + ', 1)');
radgrad.addColorStop(stop4, 'rgba(' + r + ',' + g + ',' + b + ', .4)');
radgrad.addColorStop(stop5, 'rgba(' + r + ',' + g + ',' + b + ', 0)');
ctx.fillStyle = radgrad;
ctx.arc(x, y, rad, 0, 2 * Math.PI, true);
ctx.fill();
}