D
D
Dimazsever2015-04-17 17:40:37
JavaScript
Dimazsever, 2015-04-17 17:40:37

How to make hover check on game object on canvas?

There are various mouse events in html when interacting with elements on the page. Unfortunately, this is not implemented on canvas. There are various libraries, but I would like to do without them.
How to implement such a check? Let's say I'm making a puzzle game. How can I check which square the cursor is currently over in order to highlight, for example? Need a solution without using libraries. I searched, but found something completely different. Tell me which way to dig?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilya Shatokhin, 2015-04-17
@Dimazsever

When I did something similar (but with interactive maps), I listened to an event on the canvas itself. I took coordinates from the event (event.pageX and event.pageY) and used them to search for an occurrence in the element I needed on the canvas (I kept the coordinates of the elements in memory). Here is my function code:

$("#myCanvas").on("click", function(event){
    var pt = [event.pageX, event.pageY];
    var elem = findP(pt);
});

function findP (pt) { // polygons это массив элементов (объекты с данными и координатами), в которых хранятся координаты вершин многоугольников (points).
    for (var z = 0; z < polygons.length; z++) { 			var polyz = polygons[z].points;
      for(var c = false, i = -1, l = polyz.length, j = l - 1; ++i < l; j = i)
        ((polyz[i][1] <= pt[1] && pt[1] < polyz[j][1]) || (polyz[j][1] <= pt[1] && pt[1] < polyz[i][1]))
        && (pt[0] < (polyz[j][0] - polyz[i][0]) * (pt[1] - polyz[i][1]) / (polyz[j][1] - polyz[i][1]) + polyz[i][0])
        && (c = !c);
      if (c) return polygons[z].properties;
    } return null;
  }

You can safely replace the click event with hover / mouseover, the code will be the same. It is only worth adding debounce or throttling to the handler to reduce the load.

A
Anton Shamanov, 2015-04-17
@SilenceOfWinter

Array with coordinates of objects (upper right and lower left points) iterate

K
Keyten, 2015-06-13
@Keyten

Use isPointInPath along with getting mouse coordinates.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question