webassembly使用sdl的例子

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值