Event-listener not attaching to canvas object properly [duplicate]

  canvas, css, html, javascript

l do believe to have an issue regarding an if statement that allows for the detection of where the canvas object, being the image that displays , should be located at within the canvas.

Also, l’m certain that the css alignment l’ve included is also influencing the positioning of the canvas object as the event listener seems to be affected in it’s ability to detect the button as well. There is a reproducible demo provided.

NOTE: I do want to KEEP the css alignment, canvasauto + html, body, and not remove it if possible.

var canvas = document.getElementById("c");

var ctx = canvas.getContext("2d");

var the_button = document.getElementById("the_button");
var the_background = document.getElementById("the_background");

var imageXpos = 500;
var imageYpos = 300;
var imageWidth = 110;
var imageHeight = 80;

var imagecheck_Xpos = canvas.width - imageXpos;
var imagecheck_Ypos = canvas.height - imageYpos;

window.onload = function() {
  ctx.drawImage(the_background, 0, 0, canvas.width, canvas.height);
  ctx.drawImage(the_button, imagecheck_Xpos, imagecheck_Ypos, imageWidth, imageHeight);
}

the_button_function = (event) => {
  const {
    x,
    y
  } = event;
  /* l believe the issue is here */
  if ((x >= imagecheck_Xpos && x < (imagecheck_Xpos + imageWidth)) &&
    (y >= imagecheck_Ypos && y < (imagecheck_Ypos + imageHeight))) {
    alert("<Button>")

  }
}

canvas.addEventListener('click', (e) => the_button_function(e));
html,
body {
  width: 100%;
  height: 100%;
  margin: 0px;
  border: 0;
  overflow: hidden;
  display: block;
}

.canvasauto {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<html>
<canvas id="c" width="970" height="550" class="canvasauto"></canvas>

<img style="display: none;" id="the_button" src="https://i.imgur.com/wO7Wc2w.png" />

<img style="display: none;" id="the_background" src="https://img.freepik.com/free-photo/hand-painted-watercolor-background-with-sky-clouds-shape_24972-1095.jpg?size=626&ext=jpg" />

</html>

Source: Ask Javascript Questions

LEAVE A COMMENT