简体   繁体   English

javascript mouseover矩形画布

[英]javascript mouseover rectangle canvas

I'm drawing rectangles on a canvas with Javascript. 我正在用Javascript在画布上绘制矩形。 When the user moves his mouse over one of the rectangles, a text should appear in that rectangle. 当用户将鼠标移到一个矩形上时,该矩形中将出现一个文本。 At only that rectangle (ie, not the other rectangles). 仅在该矩形处(即不在其他矩形处)。

So I managed to draw the rectangles and created the mouseover event. 因此,我设法绘制了矩形并创建了mouseover事件。 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 );

        }

    }
}

The isPointInPath method will check if the given coordinates are in any of the shapes formed by the current path. isPointInPath方法将检查给定的坐标是否为当前路径形成的任何形状。 Every rect is added to the same, single path which has already been created during your initialisation code that draws the rectangles. 每个rect都添加到在绘制矩形的初始化代码期间已经创建的相同的单个路径中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM