Maddoga
Maddoga

Reputation: 27

Canvas make event activate when mouseover specific coordinate

So what I want to do is make it that when I mouseover the canvas somewhere around (340x, 100y) it will run whatever I tell it to do inside.

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

All I have is that above, and I don't know how to make it use a specific coordinate.

Also while I'm at it, how could I make the same thing happen but with an entire array?

Thanks ahead of time for any helpful suggestions. Oh, and I'm NOT using JQuery. JUST Javascript and HTML.

Upvotes: 0

Views: 595

Answers (2)

AL-zami
AL-zami

Reputation: 9066

you can use clientX and clientY property to detect co-ordinate.If you want to do somthing with your canvas when mouse over (400,400) co-ordinate you can do it using clinetX/clientY;

how could I make the same thing happen but with an entire array

If you want to do do it with an array( if you mean checking for multiple co-ordinates),you have to create an array of object holding different co-ordinates.

      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);
                 }
            }
       });

Upvotes: 0

lucusp
lucusp

Reputation: 185

First we need to drop the ctx from your event handler like so:

canvas.addEventListener

Then I would use the mousemove event handler:

//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

    }

});

I hope this works for you or gets you on the right track!! Here's a working example: http://jsfiddle.net/fiddle_me_this/k7drc29b/

Upvotes: 1

Related Questions