Module 46: HTML with WebAssembly
Objective:
This module introduces WebAssembly (WASM) and how it integrates with HTML and JavaScript to create high-performance web applications. It covers compiling languages like C, C++, and Rust to WASM, embedding WASM in HTML, and interacting with JavaScript for seamless execution.
1. Introduction to WebAssembly (WASM)
What is WebAssembly?
WebAssembly (WASM) is a binary instruction format designed to execute at near-native speed in web browsers. It enables developers to run high-performance code in web applications, unlocking the power of languages like C, C++, and Rust within a browser.
Why Use WebAssembly with HTML?
Performance Boost: WASM executes faster than JavaScript, making it ideal for CPU-intensive tasks.
Cross-Platform: Runs on any browser supporting WebAssembly.
Portability: Convert C/C++/Rust code into WASM and use it in web applications.
Interoperability: Can communicate with JavaScript via the WebAssembly JavaScript API.
2. Setting Up WebAssembly in HTML
Step 1: Install Emscripten (for C/C++ to WASM)
Emscripten is a toolchain that compiles C/C++ code into WebAssembly.
Installation:
Download Emscripten SDK:
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh
Verify installation:
emcc -v
Step 2: Writing a Simple C Program and Compiling to WASM
C Code: "hello.c"
This program returns a simple sum of two numbers.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
Compile to WASM:
emcc hello.c -o hello.js -s EXPORTED_FUNCTIONS="['_add']" -s MODULARIZE=1
This generates:
hello.wasm (the WebAssembly binary)
hello.js (JavaScript wrapper to load WASM)
hello.wasm.wat (human-readable WASM)
Step 3: Loading WebAssembly in HTML
Now, we load our WebAssembly module into an HTML page.
HTML File: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebAssembly with HTML</title>
</head>
<body>
<h1>WebAssembly Example</h1>
<p>Result: <span id="result"></span></p>
<script src="hello.js"></script>
<script>
Module().then((module) => {
let result = module._add(5, 7);
document.getElementById("result").innerText = result;
});
</script>
</body>
</html>
Explanation:
Loads the hello.js script, which initializes WebAssembly.
Calls the compiled _add() function inside WASM.
Updates the HTML span with the result.
3. Interacting with WebAssembly from JavaScript
We can pass values from JavaScript to WebAssembly and receive output.
Example: JavaScript Calling WASM
fetch("hello.wasm")
.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes, {}))
.then(({ instance }) => {
console.log("Result from WASM:", instance.exports.add(3, 4));
});
Key Concepts:
fetch("hello.wasm"): Loads the WASM binary.
WebAssembly.instantiate(bytes, {}): Initializes WASM in JavaScript.
instance.exports.add(3, 4): Calls the WASM function.
4. Advanced WebAssembly with Rust
Instead of C/C++, you can use Rust for WebAssembly.
Step 1: Install Rust and WebAssembly Target
rustup target add wasm32-unknown-unknown
Step 2: Create a Rust WebAssembly Program
Rust File: lib.rs
#[no_mangle]
pub fn multiply(a: i32, b: i32) -> i32 {
a * b
}
Step 3: Compile to WASM
cargo build --target wasm32-unknown-unknown --release
This generates lib.wasm, which can be loaded into an HTML page.
5. Exercises and Challenges
Exercise 1: Modify the WebAssembly Function
Change the add() function to perform multiplication.
Recompile and test in HTML.
Exercise 2: Accept User Input
Create an HTML form with two input fields.
Use JavaScript to pass user input to WASM.
Display the calculated result.
Exercise 3: Use WebAssembly for Image Processing
Load an image into an HTML <canvas>.
Use WebAssembly to apply grayscale to the image.
6. Debugging and Performance Optimization
Debugging WebAssembly
Use Chrome DevTools → WebAssembly Debugging.
View .wat files (human-readable WASM).
Enable source maps in Emscripten.
Performance Optimization
Optimize Code: Use -O3 when compiling C/C++.
Reduce WASM Size: Minify with wasm-opt.
Use SIMD & Threads: Parallel processing in WASM.
7. Conclusion and Next Steps
Key Takeaways:
WebAssembly is fast and works with C, C++, and Rust.
HTML and JavaScript can communicate with WASM.
Real-world applications include gaming, AI, and high-performance computing.
Next Steps:
Experiment with memory management in WASM.
Explore WebAssembly System Interface (WASI).
Integrate WebGL for 3D rendering with WASM.
This module provides theory, step-by-step practical implementation, interactive exercises, and examples to ensure learners deeply understand WebAssembly with HTML.
No comments:
Post a Comment