Recently, a user asked an interesting question about using multiple canvas elements on a single page. Of course, the questions arises why someone should need such a thing. In practice, however, there are many useful applications (such as 3D configurators), including those from the well-known Animagraffs Studio.
This fascinating feature deserves a closer look.
What exactly is it about?
If you try to initialize multiple canvas elements in your script, you will of course generate errors because the engine uses many variables to store the operating conditions.
Here`s the idea: The user`s web browser loads one and only one engine file as usual. However, they also set specific namespaces in their scripts. These namespaces allow the engine to process its scripts as if they were separate entities working independently.
At the beginning we have to prepare a place for several canvases in the HTML body. I will use a default template that the project manager generates when a new project is created.
There must be two independent canvas elements placed on the page. Accordingly, Div containers are defined in the HTML element.
The code to be implemented is to be stored for different containers in different JavaScript files. The corresponding lines must be added to the HTML. In addition, the storage location, size and other parameters must be defined in the CSS file:
In addition, the storage location, size and other parameters must be defined in the CSS file:
And now comes the interesting part. The namespace must be set when the module is initialized in the b4w.require function, so that the engine can assign the script to the corresponding identifiers. However, internal requirement function calls should not use identifiers.
At the end, the default code generated by the project manager should look like this:
And the code for the second canvas should look like this:
The interaction between two canvases.
In the following, we will look at a more complex example where code for different canvas elements can interact with each other. We will try to start an animation on the first canvas with a mouse click in the second canvas window.
We define the external function “ext_method” to start the animation in the first canvas code:
In the second canvas code, define the animation function with Require and set the identifier of the required canvas as a parameter. Note that in this case, the Require method is called from the b4w global object.
Now we add the default code for processing the “click” event:
As you can see it is not very difficult to work with multiple canvases. You will discover amazing new possibilities.