Get the exact location of a mouse click on a canvas
HTML
<!--<canvas id='canvas' width='600' height='400'></canvas><!-- // -->
<div id='buffer'></div>
<div id='wrapper'>
<canvas id='canvas' width='600' height='400'></canvas> <!-- // -->
</div>
CSS
#buffer {
background-color: yellow;
height:500px;
}
#wrapper {
background-color: #CCCCCC;
padding:20px;
padding-left: 120px;
margin:30px;
display: inline-block;
}
#canvas {
background-color: #999999;
padding: 10px;
margin: 15px;
}
JavaScript
Math.TAU = Math.PI * 2;
function position(elem) {
var left = 0,
top = 0;
do {
left += elem.offsetLeft;
top += elem.offsetTop;
} while ( elem = elem.offsetParent );
return [ left, top ];
}
function getPos(el) {
var pl = parseInt(window.getComputedStyle(el, null).getPropertyValue('padding-left'));
var pt = parseInt(window.getComputedStyle(el, null).getPropertyValue('padding-top'));
for (var lx=0, ly=0;
el != null;
lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
return {x: lx + pl,y: ly + pt};
}
CanvasRenderingContext2D.prototype.drawCircle = function (x, y, radius) {
this.beginPath();
this.arc(x, y, radius, 0, Math.TAU);
this.fill();
//this.stroke();
}
canvas = document.getElementById('canvas');
canvas.addEventListener('click', addDot);
context = canvas.getContext('2d');
context.fillStyle = 'black';
context.fillRect(0, 0, canvas.width, canvas.height);
context.fill();
function addDot(event) {
context.fillStyle = 'white';
context.drawCircle(event.pageX - getPos(event.target).x, event.pageY - getPos(event.target).y, 4);
}