Ideas, drafts, and hacks

18 Jul 2022

Playing with Scala.js and a canvas (code)

If you look at yesterday’s article, you maybe wonder how it works. Well, the code is very straightforward. We import our dependencies for exporting the function, using the dom, and generating random numbers.

Code for creating a canvas and change color every second

Using a Scala object, we create a method called main and add an annotation to say the Scala.js compiler that we want to expose this function. Inside the function, we create a canvas object, add it to the dom, and adjust its size to fill all the space.

Next, we get the context for the canvas object and create a function that changes its color generating three random numbers (one for each value of the intensity of the color red, green, and blue).

Finally, we set that the function that changes the canvas color will run every second. And that is it. By the way, I’m using carbon for code styling.

See you next time.