From 425c40e8c776eda1ccd3010d08966e742bf77a62 Mon Sep 17 00:00:00 2001 From: suremoon Date: Fri, 4 Jul 2025 22:17:29 +0800 Subject: [PATCH] Fix: Inaccurate mouse position in raylib WASM on web pages Fixed an issue where the mouse position was inaccurate when the raylib library was compiled to WASM for web pages. Problem Cause: Upon investigation, the issue was determined to be caused by glfwSetCursorPosCallback (which is emulated in the WASM environment) returning the mouse position relative to the initial canvas size created during the InitWindow call. This means that even if the canvas element's size on the web page changed (e.g., after a window resize via CSS or JavaScript), glfwSetCursorPosCallback would still report mouse positions based on the original, fixed canvas dimensions. This led to incorrect mouse coordinates calculated by raylib's internals when the web page was not full-screen or when the Canvas element's size was dynamic. --- src/platforms/rcore_web.c | 4 ++-- src/rcore.c | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/platforms/rcore_web.c b/src/platforms/rcore_web.c index 046b79187..6f7a3d63f 100644 --- a/src/platforms/rcore_web.c +++ b/src/platforms/rcore_web.c @@ -1591,8 +1591,8 @@ static void MouseCursorPosCallback(GLFWwindow *window, double x, double y) // If the pointer is not locked, follow the position if (!CORE.Input.Mouse.cursorHidden) { - CORE.Input.Mouse.currentPosition.x = (float)x; - CORE.Input.Mouse.currentPosition.y = (float)y; + CORE.Input.Mouse.currentPosition.x = (float) x * CORE.Window.screen.width / CORE.Window.initScreen.width; + CORE.Input.Mouse.currentPosition.y = (float) y * CORE.Window.screen.height / CORE.Window.initScreen.height; CORE.Input.Touch.position[0] = CORE.Input.Mouse.currentPosition; } diff --git a/src/rcore.c b/src/rcore.c index e97ef357c..c34519c0c 100644 --- a/src/rcore.c +++ b/src/rcore.c @@ -295,6 +295,7 @@ typedef struct CoreData { Point position; // Window position (required on fullscreen toggle) Point previousPosition; // Window previous position (required on borderless windowed toggle) Size display; // Display width and height (monitor, device-screen, LCD, ...) + Size initScreen; // when init window, Screen width and height (used render area) Size screen; // Screen width and height (used render area) Size previousScreen; // Screen previous width and height (required on borderless windowed toggle) Size currentFbo; // Current render width and height (depends on active fbo) @@ -668,6 +669,9 @@ void InitWindow(int width, int height, const char *title) // Initialize window data CORE.Window.screen.width = width; CORE.Window.screen.height = height; + CORE.Window.initScreen.width = width; + CORE.Window.initScreen.height = height; + CORE.Window.eventWaiting = false; CORE.Window.screenScale = MatrixIdentity(); // No draw scaling required by default if ((title != NULL) && (title[0] != 0)) CORE.Window.title = title;