sdl的例子转成webassembly的例子
注意
1.主函数改个主循环,只有这里是嵌入的代码
emscripten_set_main_loop_arg
2.用emcc生成js和wasm
3.在h5中只需要把Module对象的cavas属性和dom元素对应上即可。
4.关于memory.wasm,参考https://github.com/guybedford/wasm-stdlib-hack
和例子:https://github.com/guybedford/wasm-intro
https://github.com/3dgen/cppwasm-book
c的代码 为
#include <SDL2/SDL.h>
#include <emscripten.h>
#include <cstdlib>
struct context
{
SDL_Renderer *renderer;
int iteration;
};
void mainloop(void *arg)
{
context *ctx = static_cast<context*>(arg);
SDL_Renderer *renderer = ctx->renderer;
// example: draw a moving rectangle
// red background
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderClear(renderer);
// moving blue rectangle
SDL_Rect r;
r.x = ctx->iteration % 255;
r.y = 50;
r.w = 50;
r.h = 50;
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255 );
SDL_RenderFillRect(renderer, &r );
SDL_RenderPresent(renderer);
ctx->iteration++;
}
int main()
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *window;
SDL_Renderer *renderer;
SDL_CreateWindowAndRenderer(255, 255, 0, &window, &renderer);
context ctx;
ctx.renderer = renderer;
ctx.iteration = 0;
const int simulate_infinite_loop = 1; // call the function repeatedly
const int fps = -1; // call the function as fast as the browser wants to render (typically 60fps)
emscripten_set_main_loop_arg(mainloop, &ctx, fps, simulate_infinite_loop);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}
编译的脚本为:
emcc core.cpp -s WASM=1 -s USE_SDL=2 -O3 -o index.js
生成index.wasm 和index.js
index.html为
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<!-- Create the canvas that the C++ code will draw into -->
<canvas id="canvas" oncontextmenu="event.preventDefault()"></canvas>
<!-- Allow the C++ to access the canvas element -->
<script type='text/javascript'>
var Module = {
canvas: (function() { return document.getElementById('canvas'); })()
};
</script>
<!-- Add the javascript glue code (index.js) as generated by Emscripten -->
<script src="index.js"></script>
<p>Minimal example of animating the HTML5 canvas from C++ using SDL through WebAssembly.</p>
</body>
</html>