dathiezer
dathiezer

Reputation: 53

javascript mouseover rectangle canvas

I'm drawing rectangles on a canvas with Javascript. When the user moves his mouse over one of the rectangles, a text should appear in that rectangle. At only that rectangle (i.e., not the other rectangles).

So I managed to draw the rectangles and created the mouseover event. It works perfectly: as soon as the mouse moves over one of the rectangles the text appears. However, the text appears in ALL rectangles... Any thought about what I'm doing wrong? There seems to be a looping problem, but I can't seem to fix it.

function handleMouseMove(e){

    mouseX=parseInt(e.clientX-offsetX);
    mouseY=parseInt(e.clientY-offsetY);

    for(var i=0;i<entities.length;i++){

        var entity=entities[i];

        ctx.rect(entity.x, entity.y, width, height);

        if(ctx.isPointInPath(mouseX,mouseY)){ 

            ctx.font = "10px Arial";
            ctx.fillStyle = "black";
            ctx.textAlign = "left";
            ctx.fillText("edit", entity.x + 5 , entity.y + 5 );

        }

    }
}

Upvotes: 0

Views: 671

Answers (1)

trincot
trincot

Reputation: 350137

The isPointInPath method will check if the given coordinates are in any of the shapes formed by the current path. Every rect is added to the same, single path which has already been created during your initialisation code that draws the rectangles.

So the effect is that once your mouse is over any of the drawings, the condition is true in each iteration of your loop.

Solve this by creating a new path in each iteration:

for(var i=0;i<entities.length;i++){
    var entity=entities[i];
    ctx.beginPath(); // <----
    ctx.rect(entity.x, entity.y, width, height);
    // ...etc

Upvotes: 2

Related Questions