emscripten-core / emscripten

Emscripten: An LLVM-to-WebAssembly Compiler
Other
25.35k stars 3.25k forks source link

(0, 0) mouse click in emscripten_set_mousedown_callback #22131

Closed 8Observer8 closed 1 week ago

8Observer8 commented 1 week ago

Version of emscripten/emsdk: 3.1.37

The following code prints (0, 0) to the console when I click on the canvas:

emcc -g main.cpp -o public/index.html

main.cpp

#include <emscripten.h>
#include <emscripten/html5.h>
#include <iostream>

int main()
{
    // Mouse Button Down:
    emscripten_set_mousedown_callback(
        "#canvas", nullptr, 0, +[](int eventType,
            const EmscriptenMouseEvent *e, void *userData) -> EM_BOOL
        {
            std::cout << e->canvasX << " " << e->canvasY << "\n";
            return EM_FALSE;
        });

    return 0;
}
sbc100 commented 1 week ago

From the comments at canvasX/canvasY it looks like they are not longer reported:

https://github.com/emscripten-core/emscripten/blob/eb47e28bd6dbbd44292f02cd096ed96401d83e63/system/include/emscripten/html5.h#L127-L129

I guess we should probably just remove them completely at this point..

8Observer8 commented 1 week ago

@sbc100 Please tell me how to get the coordinates of a mouse click inside the canvas?

sbc100 commented 1 week ago

I think you can just use targetX/targetY if you register the callback on the canvas itself like you are doing here.

8Observer8 commented 1 week ago

Thank you so much! I have missed to try it. I have tried screenX/screenY and clientX/clientY. I tried to google how to implement this in Emscripten:

        gl.canvas.onmousedown = (e) => {
            // Get coordinates of mouse pick
            const rect = gl.canvas.getBoundingClientRect();
            const mouseX = e.clientX - rect.left;
            const mouseY = e.clientY - rect.top;

But targetX/targetY works as expected. It is very nice! Thank you very much again!

emcc -g main.cpp -o public/index.html

main.cpp

#include <emscripten.h>
#include <emscripten/html5.h>
#include <iostream>

// https://github.com/emscripten-core/emscripten/issues/19266
int main()
{
    // Keyboard Key Down:
    emscripten_set_keydown_callback(
        "#canvas", nullptr, 0, +[](int eventType, const EmscriptenKeyboardEvent *e, void *userData) -> EM_BOOL {
            std::cout << "Key down: " << e->keyCode << "\n";
            return EM_FALSE;
        });

    // Mouse Button Down:
    emscripten_set_mousedown_callback(
        "#canvas", nullptr, 0, +[](int eventType,
            const EmscriptenMouseEvent *e, void *userData) -> EM_BOOL
        {
            // std::cout << "Mouse down: " << e->button << "\n";
            std::cout << e->targetX << " " << e->targetY << "\n";
            return EM_FALSE;
        });

    return 0;
}