在WebAssembly / Rust中编辑画布像素数据

时间:2018-04-20 06:18:16

标签: rust webassembly

我正在尝试使用WebAssembly和Rust尝试创建画布像素数据。作为初步实验,我试图让Rust写入其线性内存,然后我将使用它来创建一个ImageData对象,我可以写入画布。

底层Ima​​geData是Uint8Array,其中每个像素为rgba的4个数字。我使用以下结构代表生锈:

struct Pixel {
    r: u8,
    g: u8,
    b: u8,
    a: u8,
}

我已经将一个函数导出到JavaScript,它将尝试为500 x 500像素画布中的所有250,000像素着色:

#[no_mangle]
pub fn color(width: u32, height: u32) {
    for i in 0..width * height {
        let ptr = (i * 4) as u64 as *mut Pixel;
        let mut pixel = unsafe { &mut *ptr };
        pixel.r = 10;
        pixel.g = 10;
        pixel.b = 10;
        pixel.a = 255;
    }
}

这里是前端的相应HTML / JS

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <style>
        canvas {
            border: 1px solid red;
        }
    </style>
</head>

<body>
    <canvas id="canvas" height="500" width="500"></canvas>

    <script>

        const WIDTH = 500;
        const HEIGHT = 500;

        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');

        fetch('/rotate.wasm')
            .then((res) => res.arrayBuffer())
            .then((ab) => WebAssembly.instantiate(ab))
            .then(({ instance }) => {

                instance.exports.memory.grow(100);              // make memory big enough
                instance.exports.color(WIDTH, HEIGHT);

                const data = new Uint8ClampedArray(instance.exports.memory.buffer, 0, WIDTH * HEIGHT * 4)
                const imageData = new ImageData(data, 500, 500);

                ctx.putImageData(imageData, 0, 0);
            });
    </script>
</body>

</html>

结果是并非所有像素都是彩色的。只有顶部的一部分:

enter image description here

当我检查WebAssembly内存时,我可以看到它看起来像是在大约42k像素后放弃着色。

enter image description here

2 个答案:

答案 0 :(得分:3)

我想我发现了答案。无法保证线性存储器的启动可供JavaScript使用。由Rust包含在wasm二进制文件中的运行时可以自由地写入该内存位置。我通过在程序中静态分配一块内存并返回一个指向JavaScript的指针来解决我的问题,因此它知道写入的安全性。

// Statically allocate space for 1m pixels

static mut PIXELS: [Pixel; 1_000_000] = [Pixel {
    r: 255,
    g: 0,
    b: 0,
    a: 255,
}; 1_000_000];

// return pointer to JavaScript

#[no_mangle]
pub fn get_memory_offset() -> i32 {
    return unsafe { &PIXELS as *const _ as i32 };
}

动态分配内存会很好,但我还不知道该怎么做。

答案 1 :(得分:3)

您的代码将图像数据写入从位置0开始的线性存储器,您确定这样做是否安全?大多数语言在编译为WebAssembly时,都会将线性内存用于自己的运行时。

更安全的选择是创建一个表示图像的结构,然后从JavaScript代码中获取对此的引用,以便确保JS和Rust代码对齐:

https://github.com/ColinEberhardt/wasm-rust-chip8/blob/master/web/chip8.js#L124