I figure I ought to follow up with some results.  First, I got the 
suggested approach of local render + js.CopyBytesToJS 
<https://golang.org/pkg/syscall/js/#CopyBytesToJS> + update canvas from 
image to work, so thanks, Agniva and Howard!  Second, for the benefit of 
future readers of this thread, one thing that wasn't obvious to me is that 
one needs to render the image data in a browser-recognizable image format—I 
used PNG <https://en.wikipedia.org/wiki/Portable_Network_Graphics>—*not* 
raw {red, green, blue, alpha} bytes as is needed when writing directly to a 
canvas <https://www.w3schools.com/tags/tag_canvas.asp>'s image data.  
Third, I used JavaScript code like the following to update an invisible img 
<https://www.w3schools.com/tags/tag_img.asp> then copy the image data from 
there to a visible canvas:

function copyBytesToCanvas(data) {
    let blob = new Blob([data], {"type": "image/png"});
    let img = document.getElementById("myImage");
    img.onload = function() {
        let canvas = document.getElementById("myCanvas");
        let ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);
    };
    img.src = URL.createObjectURL(blob);
}

Fourth, the performance is indeed substantially faster than my previous 
approach based on using SetIndex 
<https://golang.org/pkg/syscall/js/#Value.SetIndex> to write directly to 
the canvas, even though the new approach requires the extra steps of 
encoding the image in PNG format and copying the image data from an img to 
a canvas.  The following performance data, measured with Go 1.14 and 
Chromium 80.0.3987.132 on an Ubuntu Linux system, is averaged over 10 runs:

*Old*: 686.9 ± 7.6 ms
*New*: 290.4 ± 4.1 ms (284.3 ± 4.2 on the WebAssembly side plus 6.0 ± 2.3 
on the JavaScript side)

This is the time to render a simple 800×800 gradient pattern.

I hope others find this useful.

— Scott

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/2465c1d3-9881-404f-a70d-6bee7f8225a7%40googlegroups.com.

Reply via email to