In my code I use SDL2/emscripten to make a texture in memory. Also I have a HTML canvas to render this texture. The basic flow to do that is constantly render the SDL surface in the emscripten_set_main_loop_arg() loop. But my scene doesn't change quickly, so I don't need to redraw it every cicle.
What I think: I create a surface, which doesn't attach to the canvas:
SDL_Init(SDL_INIT_EVERYTHING);
int r = TTF_Init();
if (r < 0)
{
printf("TTF_Init error: %s\n", TTF_GetError());
return;
}
//SDL_Window* window = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_HIDDEN);
//renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
surface = SDL_CreateRGBSurface(0, width, height, 32, 0, 0, 0, 0);
renderer = SDL_CreateSoftwareRenderer(surface);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderClear(renderer);
After I need to convert it to a bitmap and copy the bitmap to canvas when the scene changed. And this is the problem. How should I get bitmap from the surface? Is it right way:
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
Uint32 format;
int access;
int w, h;
SDL_QueryTexture(texture, &format, &access, &w, &h);
Uint8* pixels = (Uint8*)malloc(w * h * SDL_BYTESPERPIXEL(format));
SDL_RenderReadPixels(renderer, &surface->clip_rect, format, pixels, surface->pitch);
free(pixels);
SDL_DestroyTexture(texture);
How should I copy it to canvas? Here I tried some variants with EM_ASM, without any success...
Finally I made another renderer with a surface in the working thread. Working thread makes the scene, and when it's ready, signals to the SDL (emscripten_set_main_loop_arg) thread to be rendered. This thread copy scene into its canvas surface.