Canvas object positioning issue – JS

  canvas, javascript, resize

l believe to have a error of sorts.

Visually, the button goes off the SCREEN instead of sitting in it’s spot. The issue is the X positioning of the canvas object, being the ”, as it moves off screen when you resize the browser window from the LEFT but also the button does NOT MOVE and STAYS IN ITS PLACE when resizing the browser window from the RIGHT.

Essentially, the canvas object, ‘button’, should be secured in one place so that it stays in the same spot no matter how big or small my browser’s window is.

There is also a reproducible demo.

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 button_imageLeft = 1100;
var button_imageBottom = 150;
var button_imageWidth = 170;
var button_imageHeight = 100;
var button_offsetX, button_offsetY;

window.onload = function() {
  ctx.drawImage(the_background, 0, 0, canvas.width, canvas.height);
  drawButton();
}

initialize();


function initialize() {
  window.addEventListener('resize', resizeCanvas, false);
  resizeCanvas();
}

function drawButton() {
  button_offsetX = button_imageLeft;
  button_offsetY = canvas.height - button_imageBottom;
  ctx.drawImage(the_button, button_offsetX, button_offsetY, button_imageWidth, button_imageHeight);
}

function redraw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(the_background, 0, 0, canvas.width, canvas.height);
  drawButton();
}

function resizeCanvas() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  redraw();
}

the_button_function = (event) => {
  const {
    x,
    y
  } = event;
  if ((x >= button_offsetX && x < (button_offsetX + button_imageWidth)) &&
    (y >= button_offsetY && y < (button_offsetY + button_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;
}
<html>
<canvas id="c"></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