Handling resizing of the canvas
- SDL3 - recommended. It works for Web, Desktop, Android and so on:
int SDL_AppEvent(void *appstate, const SDL_Event *event)
{
auto *app = (AppContext *)appstate;
switch (event->type)
{
case SDL_EVENT_WINDOW_RESIZED:
{
int w = SDL_GetWindowSurface(app->window)->w;
int h = SDL_GetWindowSurface(app->window)->h;
std::cout << w << " " << h << std::endl;
break;
}
case SDL_EVENT_QUIT:
{
app->app_quit = SDL_TRUE;
break;
}
default:
{
break;
}
}
return 0;
}
- Emscripten - not recommended because it works in the browser only:
#include <emscripten.h>
#include <emscripten/html5.h>
int SDL_AppInit(void **appstate, int argc, char *argv[])
{
// ...
emscripten_set_resize_callback(
EMSCRIPTEN_EVENT_TARGET_WINDOW, nullptr, 0,
+[](int eventType, const EmscriptenUiEvent *e, void *userData) -> EM_BOOL
{
int w = e->windowInnerWidth;
int h = e->windowInnerHeight;
std::cout << w << " " << h << std::endl;
return EM_FALSE;
});
// ...
}
If you need a size of the canvas at the first resize:
- SDL3 - recommended:
bool isFirstResize = true;
int SDL_AppEvent(void *appstate, const SDL_Event *event)
{
auto *app = (AppContext *)appstate;
if (isFirstResize)
{
int w = SDL_GetWindowSurface(app->window)->w;
int h = SDL_GetWindowSurface(app->window)->h;
std::cout << w << " " << h << std::endl;
isFirstResize = false;
}
// ...
}
- Emscripten:
#include <emscripten.h>
#include <emscripten/html5.h>
bool isFirstResize = true;
int SDL_AppEvent(void *appstate, const SDL_Event *event)
{
auto *app = (AppContext *)appstate;
if (isFirstResize)
{
int w, h;
emscripten_get_canvas_element_size("#canvas", &w, &h);
std::cout << w << " " << h << std::endl;
isFirstResize = false;
}
// ...
}