简体   繁体   中英

How to check if mouse position is inside HTML5 Canvas path?

I'm new to HTML5 Canvas and Javascript. I'm currently working on a HTML5 Canvas project (I wrote a separate question about it here and here ).

The logic of the game is pretty simple: track the mouse position and if the mouse position exits the blue region, the game resets. The user starts on level 1 ( function firstLevel ). If their mouse position enters the red box region, they advance onto the next level ( return secondLevel() ). I did this previously by a hefty list of if statements that compared the mouse's x and y coordinates.

I've corrected the code to create a global constructor function I can reference in each of the level functions:

function Path(array, color) {
  let path = new Path2D();
  path.moveTo(array[0][0], array[0][1]); 
  for (i = 1; i < array.length; i++) {
    path.lineTo(array[i][0], array[i][1]);
  }
  path.lineTo(array[0][0], array[0][1]);
  return path;
} 

And its referenced in the level functions as such:

    // In the individual levels, put code that describes the shapes locally
    var big = [[350,200], [900,200], [900,250], [700,250], [600,250], [600,650], [350,650]];
    var blue = Path(big);

    var small = [[900,200], [900,250], [850,250], [850, 200], [900, 200]];
    var red = Path(small);

      // 2. create cursor
      c.beginPath();
      c.rect(mouseX, mouseY, mouseWidth, mouseHeight);
      c.fillStyle = "#928C6F";
      c.fill();

    // Local code that draws shapes:
    c.beginPath()
    c.fillStyle = '#C1EEFF';
    c.fill(blue);

    c.beginPath()
    c.fillStyle = "#FF4000";
    c.fill(red);

I want to know how can I check for the mouse position so it can run those conditional statements using the isPointInPath method? I now have a reference (refs. blue and red ) for the Canvas shape, so I'm hoping there's a way I can check if the mouse's x and y position is a point that is inside the shape/path.

Link to my project: https://github.uconn.edu/pages/ssw19002/dmd-3475/final-project/maze-page-1.html

Source code: https://github.uconn.edu/ssw19002/dmd-3475/tree/master/final-project

You could use the MouseEvent.offsetX and MouseEvent.offsetY properties of a mouse event such as mousemove . (You would need to add an event listener for mouse events to the canvas element of course.)

Then use the x and y offset values obtained to call isPointInPath like

ctx.isPointInPath(path, x, y)

where path is a return value from function Path .

While MDN lists the offset properties as "experimental" they seem to have been around since IE9 at least.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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