HOE INN
HOE INN

Reputation: 25

Problem on Canvas x, y position (JS) when setting Zoom

I'm working on canvas drawing by mouse event.

I wanted to set body tag zoom size around 80% by using

document.body.style.zoom = '80%';

But when I used this code:

The positions of X, Y are wrong.

Here's the code.

function canvasX(clientX) {

    var bound = canvas.getBoundingClientRect();

    return (clientX - bound.left) * (canvas.width / bound.width);

}


function canvasY(clientY) {

    var bound = canvas.getBoundingClientRect();

    return (clientY - bound.top) * (canvas.height / bound.height);

}

tried to give layerX, layerY as a parameter but worked bad.

Positions are setted more left(-) and top(-).

It would be great if you help me out to apply zoom size on mouse position.

Upvotes: 1

Views: 1139

Answers (1)

user128511
user128511

Reputation:

This is one way

const canvas = document.querySelector('#container canvas');
const ctx = canvas.getContext('2d');
let count = 0;

canvas.addEventListener('mousemove', (e) => {
  const pos = getElementRelativeMousePosition(e, canvas);
  ctx.fillStyle = hsl((count++ % 10) / 10, 1, 0.5);
  ctx.fillRect(pos.x - 1, pos.y - 1, 3, 3);
});

[...document.querySelectorAll('button')].forEach((elem) => {
  elem.addEventListener('click', (e) => {
    document.body.style.zoom = `${elem.textContent}`;
  });
});

function getElementRelativeMousePosition(e, elem) {
  const rect = elem.getBoundingClientRect();
  const css = getComputedStyle(document.body);
  
  return {
    x: e.clientX / css.zoom - rect.left,
    y: e.clientY / css.zoom - rect.top,
  };
}

function hsl(h, s, l) {
  return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;
}
canvas { 
  display: block;
}
#container {
  margin: 20px;
  border: 1px solid black;
  display: inline-block;
}
<div>
  <button type="button">50%</button>
  <button type="button">75%</button>
  <button type="button">100%</button>
  <button type="button">125%</button>
  <button type="button">150%</button>
</div>
<div id="container">
  <canvas></canvas>
</div>

but note that zoom is a non-standard property and is not supported in all browsers. It is not supported in Firefox at all.

Upvotes: 2

Related Questions