画布使事件在鼠标悬停在特定坐标上时激活

Canvas make event activate when mouseover specific coordinate

本文关键字:坐标 激活 悬停 布使 事件 鼠标      更新时间:2023-09-26

所以我想做的是,当我将鼠标悬停在画布上时(340x,100y),它会运行我告诉它在里面做的任何事。

    ctx.canvas.addEventListener('mouseover', function(event){
            ctx.clearRect(0, 0, 1000, 1000);
    });

我所拥有的只是上面的内容,我不知道如何使用特定的坐标来使其。

另外,当我在使用它时,我怎么能让同样的事情发生,但整个阵列?

提前感谢您提供任何有用的建议。哦,我没有使用JQuery。只是Javascript和HTML。

首先,

我们需要从事件处理程序中删除ctx,如下所示:

canvas.addEventListener

然后我将使用 mousemove 事件处理程序:

//This is to get the position of the canvas to (better) accurately
//reflect the mouse coordinates assumes NOT nested in a div or wrapper
var canvasPos = {
    x: canvas.offsetLeft,
    y: canvas.offsetTop
 };
canvas.addEventListener('mousemove', function(e){
    var mousePoint = {
        x: e.pageX - canvasPos.x,
        y: e.pageY - canvasPos.y
    };
    if(mousePoint.x == 340 && mousePoint.y == 100){
       //do whatever it is you want your code to do
    }
});

我希望这对您有用或让您走上正轨!!下面是一个工作示例:http://jsfiddle.net/fiddle_me_this/k7drc29b/

您可以使用

clientXclientY属性来检测坐标。如果您想在鼠标悬停在 (400,400) 坐标上时对画布执行某些操作,您可以使用 clinetX/clientY 来完成;

我怎么能让同样的事情发生,但有一个完整的数组

如果你想用一个array来做(如果你的意思是检查多个坐标),你必须创建一个包含不同坐标的对象数组。

      var x=[30,45,50];  // define desired X co-ordinates
      var y=[40,50,75];  // define desired Y co-ordinates
      var coObj=[];   // an empty array to hold all possible (x,y) co-ordinates
       x.forEach(function(el,index){
             coObj.push({x:el,y:y[index]});  //create an array of objects and insert them to coObj array
       })
       canvas.addEventListener('mousemove', function(event){
            var xpos=event.clientX-this.offsetLeft;  //here this refers to current canvas object
            var ypos=event.clientY-this.offsetTop;

            for(i=0;i<coObj.length;i++){
                 if(xpos==coObj[i].x && ypos==coObj[i].y){  // check for possible co-ordinate match
                     alert('coOrdinate found !!');
                     ctx.clearRect(0, 0, 1000, 1000);
                 }
            }
       });