Как точно определить положение мыши относительно элемента HTML в реакции?Javascript

Форум по Javascript
Ответить
Anonymous
 Как точно определить положение мыши относительно элемента HTML в реакции?

Сообщение Anonymous »

У меня есть приложение, содержащее холст, на котором я рисую, и мне хотелось бы иметь возможность точно отслеживать положение мыши. Проблема, с которой я сталкиваюсь, заключается в том, что чем дальше вы продвигаетесь в правый нижний угол, тем менее точным становится отслеживаемое положение. Вот демонстрационный компонент, который воспроизводит проблему:

Код: Выделить всё

import {type MouseEvent, useEffect, useRef, useState} from "react";
import {Col, Container, Row} from "react-bootstrap";

export interface Coordinate {
x: number, y: number
}

export default function Dev() {
const MouseTracker = () => {
const canvas= useRef(null);
const screenBuffer = useRef(null);
const [mp, setMp] = useState({x: 0, y: 0});
const resizeCanvas = () => {
screenBuffer.current!!.width = window.innerWidth;
screenBuffer.current!!.height = window.innerHeight;
canvas.current!!.width = window.innerWidth;
canvas.current!!.height = window.innerHeight;
}
const render = () => {
const ctx: CanvasRenderingContext2D = screenBuffer.current!!.getContext("2d")!!;
resizeCanvas()
ctx.reset();
ctx.fillStyle = "#000000";
ctx.strokeStyle = "#000000"
markMouse(ctx, mp.x, mp.y)
const visibleContext = canvas.current!!.getContext("2d")!!;
visibleContext.clearRect(0, 0, canvas.current!!.width, canvas.current!!.height);
visibleContext.drawImage(screenBuffer.current!!, 0, 0);
}
useEffect(() => { screenBuffer.current = document.createElement("canvas"); }, []);
useEffect(() => { requestAnimationFrame(render) }, [mp]);
return  setMp(positionInComponent(e))}>;
}
return 

Some header bar





}

function markMouse(ctx: CanvasRenderingContext2D, x: number, y: number) {
ctx.beginPath()
ctx.arc(x, y, 3, 0, 2*Math.PI);
ctx.strokeText(`(${x.toFixed(2)},${y.toFixed(2)})`, x + 10, y - 10)
ctx.fill()
ctx.stroke()
ctx.closePath()
}

function positionInComponent(e: MouseEvent): Coordinate {
const bounds = e.currentTarget.getBoundingClientRect();
return {
x: e.clientX - bounds.left,
y: e.clientY - bounds.top
}
}
Я пробовал заменить вычисления в PositionInComponent ответами, найденными здесь и здесь, но у них возникла та же проблема. Я также пробовал масштабировать положение x и y по ширине/высоте элемента, и это также привело к той же проблеме. Есть ли способ обеспечить точное отслеживание мыши?


Подробнее здесь: https://stackoverflow.com/questions/798 ... ement-in-r
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»