Wasm initialization

The code to compile the Wasm file and populate the <canvas> element is shown as follows:

methods: {
// Create a new Image instance to pass into the drawImage function
// for the <canvas> element's context:
loadImage(imageSrc) {
const loadedImage = new Image();
loadedImage.src = imageSrc;
return new Promise((resolve, reject) => {
loadedImage.onload = () => resolve(loadedImage);
loadedImage.onerror = () => reject();
});
},

// Compile/load the contents of main.c and assign the resulting
// Wasm module instance to the components this.instance property:
async initializeWasm() {
const ctx = this.$refs.canvas.getContext('2d');

// Create Image instances of the background and spaceship.
// These are required to pass into the ctx.drawImage() function:
const [bouncer, background] = await Promise.all([
this.loadImage(spaceshipImage),
this.loadImage(backgroundImage)
]);

// Compile the C code to Wasm and assign the resulting
// module.exports to this.instance:
const { width, height } = this.bounds;
return wasm
.init(imports => ({
...imports,
_jsFillRect(x, y, w, h) {
ctx.drawImage(bouncer, x, y, w, h);
},
_jsClearRect() {
ctx.drawImage(background, 0, 0, width, height);
}
}))
.then(module => {
this.instance = module.exports;
return Promise.resolve();
});
},
...

There are additional functions defined in the methods key of the component, but for now we'll focus on the code that compiles the imported C file to Wasm. After Image instances are created for the spaceship and background images, the main.c file (imported as .wasm) is compiled to a Wasm module and the resulting exports is assigned to this.instance. Once these operations complete, the start() function can be called from the exported Wasm module. Since the initializeWasm() function calls the <canvas> element's getContext() function, the component needs to be mounted before this function can be called. Let's review the rest of the methods definitions and the mounted() event handler.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset