1

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.

fiza khan
  • 1,280
  • 13
  • 24
HOE INN
  • 25
  • 6

1 Answers1

2

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.

gman
  • 100,619
  • 31
  • 269
  • 393
  • Thx for your comment. Seems like this zoom is working on canvas. But I did 80% zoom on style cause I need to minimize entire body elements. So that's why zoom of canvas is changed and I wanna figure out this problem!! – HOE INN Apr 11 '19 at 06:23
  • This is what I wanted. Thx for help! – HOE INN Apr 11 '19 at 06:37
  • After running the code snippet above, set zoom: .75 on the HTML tag, and see how there is a crazy offset between the mouse and the actual shape that gets drawn. That is my current predicament. Any idea how to sort that? – Brant Nov 19 '19 at 21:14
  • 1
    Don't set zoom If you're doing non-common CSS stuff like 3D transforms and zoom the problem becomes much harder. See https://stackoverflow.com/questions/55654650/how-to-get-a-canvas-relative-mouse-position-of-a-css-3d-transformed-canvas – gman Nov 20 '19 at 03:18