Search code examples
emscripten

How to retrieve in-browser size of Emscripten canvas?


I've been going over this for a while and I can't seem to find out how to achieve this.

There's a very clearly titled emscripten_get_canvas_size, which does not do what I'd expect it to do. The actual Emscripten canvas element has been set to have a width and height of 100%, but if I retrieve the width and height through emscripten_get_canvas_size, I simply get the width and height of the GLFW window that is being shown inside the canvas, not the actual dimensions of what the canvas has scaled it to.

I would like to get the actual canvas size as shown in the browser, so that I can call glfwSetWindowSize to scale the viewport to fill the entire browser window.

Even if I set the canvas to be 100x100px, emscripten_get_canvas_size only returns the 1920x1080 I've set through glfwSetWindowSize at the start of the program.

I'm probably missing something obvious, but what?


Solution

  • I have zero knowledge in GUI programming using Emscripten but you can make your own functions to get HTML canvas size. For example:

    // These are JavaScript code in C/C++ file
    #include <emscripten.h>
    EM_JS(int, canvas_get_width, (), {
      return yourCanvasElement.width;
    });
    
    EM_JS(int, canvas_get_height, (), {
      return yourCanvasElement.height;
    });
    
    // Then call
    int width = canvas_get_width();
    int height = canvas_get_height();
    

    You can learn how to create JS codes in C/C++ code in the official document.