0

I'm trying to find out where the user clicked on the canvas then display some stuff based on that. As you can see in my code I tried using xy coordinates but whenever I click somewhere else sharing the same x or y coordinate it alerts. Is it possible to have multiple canvases overlap each other or use different shapes that will trigger an event if mouse down on them?

function doMouseDown(event) {
  var canvas_x = event.pageX;
  var canvas_y = event.pageY;


  if ((canvas_x <= 351 || canvas_x >= 346) && (canvas_y <= 155 || canvas_y >= 120)) {

    alert("You are at *insert place on map*");

  }

  function startCanvas() {
    var c = document.getElementById("mycanvas");
    c.addEventListener("mousedown", doMouseDown, false);
    var ctx = c.getContext('2d');

    ctx.strokeStyle = "rgba(0,0,0,0.4)";
    ctx.fillStyle = "rgba(0,0,0,0.4)";
    var x = 340;
    var y = 120;
    var width = 100;
    var height = 30;

    var image = new Image();
    image.src = "image.gif";
    image.onload = function() {
      ctx.drawImage(image, 0, 0);
 
    };



  }
<html>

<head>
  <title>TODO supply a title</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script type="text/javascript">
  </script>

</head>

<body onload="startCanvas()">
  <canvas id="mycanvas" height="1000" width="1500">Not supported </canvas>
</body>

</html>
Jamy
  • 21
  • 6
  • Possible duplicate of [How do I get the coordinates of a mouse click on a canvas element?](https://stackoverflow.com/questions/55677/how-do-i-get-the-coordinates-of-a-mouse-click-on-a-canvas-element) – Randy Casburn Feb 24 '18 at 16:44

1 Answers1

0

It looks like the issue you are having is with your if statement.

Instead of having if (x < number || x > number) you should have it if (x < number && x > number) because you want to know if the user clicked inside something.

By the way, I highly recommend putting your if statement like this:

if (leftBound <= x && x <= rightBound)

This way, visually, it looks like x is between two numbers.

Here's a fiddle to show you a simple example of how to do what you're trying to do: https://jsfiddle.net/joseph4tw/e9fmdru2/15/

Here's the snippet from that:

Html:

<canvas id="myCanvas" height="400" width="400"></canvas>

Css:

canvas {
  background-color: #d0d0d0;
}

JS:

const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
const canvasX = canvas.offsetLeft;
const canvasY = canvas.offsetTop;

context.fillStyle = 'green';
context.fillRect(10, 10, 100, 100);

canvas.addEventListener('click', function(event) {
    const mouseX = event.clientX - canvasX;
    const mouseY = event.clientY - canvasY;

    if ((10 <= mouseX && mouseX <= 100) && (10 <= mouseY && mouseY <= 100)) {
      console.log('clicked inside square');
    } else {
      console.log('clicked outside of square');
  }
});
Joseph
  • 5,070
  • 1
  • 25
  • 26