I have the following code that gets the cursor position on a canvas
element. The code works fine in Chrome, but in Firefox, the e.nativeEvent.offsetX
is 0
inside the set state function and outside is normal.
I know that the solution would be to store the offsets and then use them, but I’m curious if this is a bug or why it is not “supposed” to work.
Thank you
import React, { useEffect, useRef, useState } from "react";
const DataFirefoxNotWorking = () => {
const [properties, setProperties] = useState(() => ({
key1: 0,
key2: 0,
key4: 0,
key3: 0,
coordinates: { x: null, y: null },
}));
const canvasRef = useRef();
const mouseMove = (e) => {
console.log({ x: e.nativeEvent.offsetX, y: e.nativeEvent.offsetY }); // This are shown correctly
setProperties((oldProperties) => ({
...oldProperties,
coordinates: { x: e.nativeEvent.offsetX, y: e.nativeEvent.offsetY },
// In Firefox this two are 0
// In Chrome works
}));
};
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas.getContext("2d");
canvas.width = 300;
canvas.height = 500;
ctx.font = "50px Arial";
ctx.strokeText(`x: ${properties.coordinates.x}`, 10, 50);
ctx.strokeText(`y: ${properties.coordinates.y}`, 10, 100);
}, [properties.coordinates]);
return (
<div>
<canvas
style={{ position: "relative" }}
ref={canvasRef}
onMouseMove={mouseMove}
/>
</div>
);
};
export default DataFirefoxNotWorking;