-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
125 lines (102 loc) · 3 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<!DOCTYPE html>
<html>
<head>
<script type="module">
async function init() {
let loadedWasmModule = null;
let image = null
const width = 600;
const height = 600;
const wasmFileInput = document.getElementById("wasmFile");
const canvas = document.getElementById("demo-canvas");
const ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
canvas.addEventListener("click", () => {
wasmFileInput.click();
})
wasmFileInput.addEventListener("change", () => {
loadWasm({ file: wasmFileInput.files[0] });
})
canvas.addEventListener("drop", async (e) => {
e.preventDefault();
const file = e.dataTransfer.files[0];
loadWasm({ file });
});
async function loadWasm({
file,
url
}) {
const importObject = {
env: {
fillStyle(r, g, b, a) {
ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`
},
fillRect(x, y, width, height) {
ctx.fillRect(x, y, width, height)
}
}
}
if (file) {
const { instance } = await WebAssembly.instantiateStreaming(
fetch(URL.createObjectURL(file)),
importObject
);
loadedWasmModule = instance;
} else if (url) {
const { instance } = await WebAssembly.instantiateStreaming(
fetch(url),
importObject
);
loadedWasmModule = instance;
}
let buffer_address = loadedWasmModule.exports.BUFFER?.value;
if (!buffer_address) {
buffer_address = loadedWasmModule.exports.get_buffer();
}
image = new ImageData(
new Uint8ClampedArray(
loadedWasmModule.exports.memory.buffer,
buffer_address,
4 * width * height,
),
width,
);
}
canvas.addEventListener("dragover", (e) => {
e.preventDefault();
});
ctx.font = "24px Arial";
ctx.fillStyle = "black";
const text = "Click to upload wasm module here";
const x = (canvas.width - ctx.measureText(text).width) / 2;
const y = canvas.height / 2;
ctx.fillText(text, x, y);
const draw = () => {
if (loadedWasmModule && image) {
ctx.putImageData(image, 0, 0);
loadedWasmModule.exports.draw();
}
requestAnimationFrame(draw);
};
draw();
}
init();
</script>
<style>
html,
body {
margin: 0;
font-family: 'Courier New', Courier, monospace;
}
</style>
</head>
<body style="margin: 0">
<input type="file" id="wasmFile" style="display: none;">
<div style="display: flex; align-items: center; justify-content: center; height: 100vh; flex-direction: column;">
<h1>WASM Art</h1>
<canvas id="demo-canvas"></canvas>
<p>See Readme on <a href="https://github.com/adamjberg/wasm-art">Github</a></p>
</div>
</body>
</html>