The remaining methods definitions and mounted() event handler function are shown as follows:
...
// Looping function to move the spaceship across the canvas.
loopRectMotion() {
setTimeout(() => {
this.instance.moveRect();
if (this.instance.getIsRunning()) this.loopRectMotion();
}, 15 - this.speed);
},
// Pauses/resumes the spaceship's movement when the button is
// clicked:
onActionClick(event) {
const newIsRunning = !this.instance.getIsRunning();
this.instance.setIsRunning(newIsRunning);
event.target.innerHTML = newIsRunning ? 'Pause' : 'Resume';
if (newIsRunning) this.loopRectMotion();
}
},
mounted() {
this.initializeWasm().then(() => {
this.instance.start(
this.bounds.width,
this.bounds.height,
this.rect.width,
this.rect.height
);
this.loopRectMotion();
});
},
Once the Wasm module is compiled, the start() function is accessible on this.instance. The bounds and rect dimensions are passed into the start() function, and then the loopRectFunction() is called to start moving the spaceship. The onActionClick() event handler function pauses or resumes the movement of the spaceship based on whether or not it's currently in motion.
The loopRectMotion() functions in the same way as the example code from Chapter 5, Creating and Loading a WebAssembly Module, except the speed is now adjustable. The 15 - this.speed calculation, which dictates the timeout length, may look a little strange. Since the movement speed of the image is based on the amount of time that elapses between function calls, increasing this number would actually slow down the spaceship. Consequently, this.speed is subtracted from 15, which was chosen because it's slightly greater than 10 but won't turn the spaceship into a blur if this.speed is increased to the maximum. That's it for the component logic; let's move on to the rendering section of the code where the template is defined.