1

Нужно получить координаты относительно блока canvas, а не от самой области просмотра

let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
canvas.style.width = canvas.offsetWidth +'px';
canvas.style.height = canvas.offsetHeight +'px';
let canvasWidth = canvas.width = canvas.offsetWidth * 2;
let canvasHeight = canvas.height = canvas.offsetHeight * 2;

canvas.addEventListener('mousemove', (e) => {
  document.querySelector('.title').innerHTML = `X: ${e.clientX}, Y: ${e.clientY}`;
});
#canvas {
  width: 200px;
  height: 100px;
  border: 1px solid #000;
  margin: 20px;
}
<canvas id="canvas"></canvas>
<div class="title"></div>

1
  • e.pageX - canvas.offsetLeft 19 апр 2021 в 11:21

1 ответ 1

3

Как-то так:

let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
canvas.style.width = canvas.offsetWidth + 'px';
canvas.style.height = canvas.offsetHeight + 'px';

function relativeCoors(ev) {
  return {
    x: ev.pageX - ev.target.offsetLeft,
    y: ev.pageY - ev.target.offsetTop
  };
}

canvas.addEventListener('mousemove', (e) => {
  const { x, y } = relativeCoors(e);
  document.querySelector('.title').innerHTML = `X: ${x}, Y: ${y}`;
});
canvas {
  border: 2px solid black;
}
<canvas id="canvas" width="400" height="200"></canvas>
<div class="title"></div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.