Graphics with WASM

WASM Helper Function

(func $toPixel (export "toPixel") (param $x i32) (param $y i32) (param $size i32) (result i32)
        (i32.mul
            (i32.add
                (i32.mul 
                    (get_local $y)
                    (get_local $size)
                )
                (get_local $x)
            )
            (i32.const 4)
        )
    )

    (func $setPixel (export "setPixel") (param $x i32) (param $y i32)(param $c i32) (param $size i32)
        (i32.store
            (call $toPixel (get_local $x) (get_local $y) (get_local $size))
            (get_local $c)
        )
    )

    (func $getPixel (export "getPixel") (param $x i32)(param $y i32) (param $size i32) (result i32)
        (i32.load
            (call $toPixel (get_local $x) (get_local $y)(get_local $size))
        )
    )

WASM i32 to RGBA


        (local $r i32)
        (local $g i32)
        (local $b i32)
        (local $a i32)
                (i32.and
                        (call $getPixel (get_local $x)(get_local $y)(get_local $size)) 
                        (i32.const 255)
                    )
                    set_local $r
                    (i32.shr_u 
                        (i32.and
                            (call $getPixel (get_local $x)(get_local $y)(get_local $size)) 
                            (i32.const 65280)
                        )
                        (i32.const 8)
                    )
                    f32.convert_s/i32
                    (i32.shr_u 
                        (i32.and
                            (call $getPixel (get_local $x)(get_local $y)(get_local $size)) 
                            (i32.const 16711680)
                        )
                        (i32.const 16)
                    )
                    set_local $b
                    (i32.shr_u 
                        (i32.and
                            (call $getPixel (get_local $x)(get_local $y)(get_local $size)) 
                            (i32.const 4278190080)
                        )
                        (i32.const 24)
                    )
                    set_local $a

Javascript (draw to canvas)

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
fetch('out2.wasm').then(response =>
    response.arrayBuffer()
  ).then(bytes =>
    WebAssembly.instantiate(bytes, importObject)
  ).then(results => {
    results.instance.exports.main();
    var buffer = memory.buffer.slice(0, size*size*4);
    const imgData = new ImageData(new Uint8ClampedArray(buffer), size, size);
    ctx.putImageData(imgData, 0, 0);
  });