学んだ全てを組み合わせて、赤い四角を画面に描画する例を考えます。
登録すべき関数はこのようになります。
let get_2d_context = register_function("
(context, selectorStart, selectorEnd) => {
let selector = context.getUtf8FromMemory(
selectorStart, selectorEnd
);
let domEl = document.querySelector(selector);
let ctx = domEl.getContext("2d");
let objHandle = context.storeObject(ctx);
return objHandle;
}");
let set_context_color = register_function("
(context, ctxHandle, colorStart, colorEnd) => {
let color = context.getUtf8FromMemory(
colorStart, colorEnd
);
let ctx = context.getObject(ctxHandle);
ctx.fillStyle = color;
}");
let draw_rect = register_function("
(context, ctxHandle, x, y, width, height) => {
let ctx = context.getObject(ctxHandle);
ctx.fillRect(x, y, width, height);
}");