Michael Paccione Michael Paccione - 2 months ago 6
Javascript Question

Canvas Mouseover via Coords bugged for 3/4 buttons

Please see the fiddle below, expand the viewing window as much as possible. I am trying to get it so I can hover over an arrow and click it. I currently have red squares as the hover coords. Unfortunately this only works on the #0 arrow box. I have no clue why this doesn't work on the other 3 boxes. The console logs output and you can see the mouse and hover coords match and update but the style change of cursor: pointer doesn't work!


(Example Console Output - See Code Below)

i: 1

coordsObj.arrows[i]: 116,548

mouseX: 171

mouseY: 569

// Capture Clicks
document.addEventListener('mousemove', function(e){

// console.log("mouseX:"+mouseX+", "+mouseY);

for (var i = coordsObj.arrows.length - 1; i >= 0; i--) {
// console.log("coordsObj: "+[coordsObj.arrows[i-1], coordsObj.arrows[i]]);
// console.log("mousePos: "+[mouseX, mouseY]);
var mouseX = e.pageX,
mouseY = e.pageY,
arrowX = coordsObj.arrows[i][0],
arrowY = coordsObj.arrows[i][1],
radius = 50;

// Debugging
console.log("i: "+i);
console.log("coordsObj.arrows[i]: "+coordsObj.arrows[i]);
console.log("mouseX: "+mouseX);
console.log("mouseY: "+mouseY);

ctx.fillStyle = "red";
ctx.fillRect(arrowX-(2*radius), arrowY-radius, radius, radius);
textObj.draw(i, arrowX, arrowY, 24, "#fff");

// Arrow Radius Hover
if (mouseX > (arrowX - radius) && mouseX < (arrowX + radius) && mouseY > (arrowY - radius) && mouseY < (arrowY + radius)){
body.style.cursor = "pointer";
} else {
body.style.cursor = "default";




The problem is that you are setting the cursor for each location. So when mouse is over boxes at the beginning of the loop you set the cursor to pointer, but the very next box will always not be under the mouse because the mouse is allready over another.

Assuming you need to loop all items for rendering, because if not you could just break out of the loop with break to fix your problem you just

need to create a variable called cursor before the loop set to the default

var cursor = "default";  // Add this befor the loop

then in the loop remove the else part and just set the cursor if need be

for (var i = coordsObj.arrows.length - 1; i >= 0; i--) {
     // your loop logic....       

     if (mouseX > (arrowX - radius) && mouseX < (arrowX + radius) && mouseY > (arrowY - radius) && mouseY < (arrowY + radius)){
          // mouse over button
          cursor = "pointer"; // set the cursor
     } // else {  // this was the bit turning off the cursor so removing it
     //   body.style.cursor = "default";

}  // end of loop

Then after the loop is done set the cursor and your problem is solved..

body.style.cursor = cursor; // now set the cursor and if over a button 
                                // it will be correct

Happy programing... :)