| 1 | <!DOCTYPE html> |
| 2 | <html lang="en"> |
| 3 | <head> |
| 4 | <meta charset="UTF-8" /> |
| 5 | <meta http-equiv="X-UA-Compatible" content="IE=edge" /> |
| 6 | <meta name="viewport" content="width=device-width, initial-scale=1.0" /> |
| 7 | <title>V Mandelbrot WebAssembly Example</title> |
| 8 | </head> |
| 9 | <body> |
| 10 | <p>Below you should see the picture of the Mandelbrot set, |
| 11 | <br>calculated in WASM, and shown in a Canvas element.</p> |
| 12 | <canvas |
| 13 | id="canvas" |
| 14 | width="400" |
| 15 | height="400" |
| 16 | style="image-rendering: crisp-edges" |
| 17 | ></canvas> |
| 18 | <script> |
| 19 | var canvas = document.getElementById("canvas"); |
| 20 | var ctx = canvas.getContext("2d"); |
| 21 | ctx.font = "32px serif"; |
| 22 | ctx.fillText("Please wait...", 100, 250); |
| 23 | var memory; |
| 24 | |
| 25 | function get_string(ptr, len) { |
| 26 | const buf = new Uint8Array(memory.buffer, ptr, len); |
| 27 | const str = new TextDecoder("utf8").decode(buf); |
| 28 | return str; |
| 29 | } |
| 30 | |
| 31 | const env = { |
| 32 | canvas_x: () => canvas.width, |
| 33 | canvas_y: () => canvas.height, |
| 34 | setpixel: (x, y, c) => { |
| 35 | ctx.fillStyle = "rgba(1,1,1," + c / 255 + ")"; |
| 36 | ctx.fillRect(x, y, 1, 1); |
| 37 | }, |
| 38 | __writeln: (ptr, len) => { |
| 39 | console.log(get_string(ptr, len)); |
| 40 | }, |
| 41 | __panic_abort: (ptr, len) => { |
| 42 | throw get_string(ptr, len); |
| 43 | }, |
| 44 | }; |
| 45 | |
| 46 | WebAssembly.instantiateStreaming(fetch("mandelbrot.wasm"), { |
| 47 | env: env, |
| 48 | }).then((res) => { |
| 49 | console.log(env.canvas_x()) |
| 50 | console.log(env.canvas_y()) |
| 51 | memory = res.instance.exports["memory"]; |
| 52 | console.time("main.main"); |
| 53 | res.instance.exports["main.main"](); |
| 54 | console.timeEnd("main.main"); |
| 55 | }); |
| 56 | </script> |
| 57 | </body> |
| 58 | </html> |
| 59 | |