此article演示了如何从C程序访问WebAssembly中的DOM:
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
unsigned int EMSCRIPTEN_KEEPALIVE IncrementClickCountOnValue()
{
// Static variable that hold how many times this function was clicked
static int clicks=0;
// Modify the DOM, through a Javascript call provided by EM_ASM_, getElementById is the DOM API used
EM_ASM_( {document.getElementById("run").value='Webassembly click count: '+$0}, ++clicks );
return 1;
}
如果编译(emcc dom.c -O1 -s MODULARIZE=1 -s WASM=1 -o dom.js
)并运行(emrun --no_browser --port 8080 .
),它会按预期工作。
在没有C的情况下我该怎么做? e。 WebAssembly text format中的EM_ASM_( {document.getElementById("run").value='Webassembly click count: '+$0}, ++clicks );
等于什么?
答案 0 :(得分:4)
没有纯粹的WebAssembly文本格式的等效项,因为WebAssembly环境对DOM(或任何浏览器API)或如何操纵它一无所知。
WebAssembly可以执行的操作是从其宿主环境(例如浏览器)导入功能。然后,您可以使用call
指令从WebAssembly中调用这些函数,方法是提供导入的函数索引或名称。
这是在WebAssembly中增加静态(全局)然后基于计数更新DOM的示例:
;; clicks.wat
(module
;; import the updateClickCount function from JavaScript land
(import "button" "updateClickCount"
(func $updateClickCount
(param $x i32)
)
)
;; Define a mutable static i32 initialized at 0
(global $count (mut i32) (i32.const 0))
;; Define and export a function to JS land
(func (export "onClick")
;; Increment the global count
get_global $count
i32.const 1
i32.add
set_global $count
;; Push the count on the stack and call the imported function
get_global $count
call $updateClickCount
)
)
这可能是要加载和设置导入并连接到DOM的相应HTML / JS:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Clicks</title>
</head>
<body>
<button id="click">CLICK ME</button>
<p id="numclicks"></p>
<script>
// This is what we'll make available to wasm
const imports = {
button: {
updateClickCount: (num) => document.getElementById('numclicks').innerHTML = num.toString()
}
};
WebAssembly.instantiateStreaming(fetch('clicks.wasm'), imports)
.then(obj => {
const exports = obj.instance.exports;
// When the button is clicked, call the function in wasm
document.getElementById('click').addEventListener('click', () => {
exports.onClick();
});
}).catch((err) => console.error(err));
</script>
</body>
</html>
WebAssembly Studio示例(单击生成并运行):https://webassembly.studio/?f=ff0fei4xgd9