Problem with not getting accurate mouse coordinates: using HTML5 canvas when resizing the page
P粉752290033
P粉752290033 2023-09-12 12:20:33
0
1
726

I want to create this Pixel Effect from a front-end expert.

Although I was able to achieve the entire pixel effect on a full screen canvas:

const canvas = getElementById('canvas');

canvas.height = window.innerHeight; // 给画布设置全屏高度
canvas.width= window.innerWidth; // 给画布设置全屏宽度

And it’s easy to get the coordinates of the mouse

const mouse = {
  x: undefined,
  y: undefined
}
canvas.addEventListner('mousemove', function(e) {
  mouse.x = e.x;
  mouse.y = e.y;
}

At this time the width and height of the canvas are equal to the document, so it is easy to obtain the accurate coordinates of the mouse. But when I try to use dimensions of 800px Accuracy of what appears on the above website. There are also some issues related to resizing.

I want to know how to maintain mouse accuracy.

Thank you for your help.

P粉752290033
P粉752290033

reply all(1)
P粉769045426

I believe that when you use e.x and e.y, even if used in the canvas's event listener, they return the mouse coordinates relative to the upper left corner pixel of the entire page, not just the coordinates of the canvas. If by "messed up" you mean the pixel effect is offset in some fixed direction no matter where you click, then this is probably your problem and you should replace e.x and e.y with e.clientX and e.clientY . The "client" in e.clientX refers to the element targeted by the listener, and specifies that the event coordinates are given relative to the element rather than the page. If the question arises any other way, then I guess I don't have the answer.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template