Getting the mouse coordinates on the canvas always works unless I have to scroll and then it goes wrong. y can end up being a negative number while it is on the canvas. Here is my code:
code block creating canvas:
var width = (document.getElementById('assessmentSectionForm' + platform).clientWidth);
var height = Math.round(theSection.thePicture.ySize * (width / theSection.thePicture.xSize))
var canvas = buildCanvas(Math.round(width), height, false, true);
//var canvas = document.getElementById('assessmentImage');
var ctx = canvas.getContext("2d");
_context = ctx;
_canvas = canvas;
canvas.addEventListener("mousedown", relMouseCoords, false);
function getting coordinates:
function relMouseCoords(event) {
var totalOffsetX = 0;
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var sect = _currentSection;
var currentElement = this;
do {
totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
} while (currentElement = currentElement.offsetParent)
if (event.pageX || event.pageY) {
canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY;
}
//alert( 'x: ' + canvasX + ' y: ' + canvasY);
for (var x = 0; x < _currentSection.allHotSpots.length; x++) {
if (_currentSection.allHotSpots[x].myPicZoom === _currentPicZoomCode) {
scaleTheHotSpot(_currentSection.allHotSpots[x], _currentSection.thePicture);
}
}
for (var i = 0; i < _currentSection.allHotSpots.length; i++) {
if (canvasX > _currentSection.allHotSpots[i].topLeft[0] &&
canvasX < _currentSection.allHotSpots[i].bottomRight[0] &&
canvasY > _currentSection.allHotSpots[i].topLeft[1] &&
canvasY < _currentSection.allHotSpots[i].bottomRight[1] &&
_currentSection.allHotSpots[i].myPicZoom === _currentPicZoomCode) {...
The rest of relMouseCoords is irrelevant because the mouse coords should be correct before I get to where I cut it off. Why does this code not account for scrolling? It looks like it should. I got it from This stack overflow answer. It is worth mentioning I am building a Telerik Mobile app, however I find the javascript to most of the time work the same as it would in a web page. If there is no obvious reason for the fault in this code, I may be best asking on the Telerik Forum.