Simple interactive element

Carlos Eduardo González Alvarez
cegonzalez13
Published in
3 min readFeb 13, 2018

Explaining the process of making a simple interactive element in WebGL

In this exercise we will be explaining how to achieve interactivity in a 3D Model, made with the WebGL API.

Here we can find the code we are going to talk about with more detail and with the option to see it working.

The first thing we have to do is set some variables that are going to change over time depending on where the user clicks on the canvas. We can do this by defining a position in X and a position in Y:

Initialization of variables for clicking

Now, we are going to use this variables inside the creation of the cube. We do this in the translate function, where we can establish the current position of the cube considering its view Matrix:

Setting up the clicks

The only thing we have left for our example to work is recognize where is the user clicking inside the canvas. For this, we can use a Javascript function called addEventListener, and set it for our recently created canvas in the main() function. With this function, we can do something every time the user clicks a point inside the canvas, and we can easily know the X and Y coordinates where the click has been made. Our job is to update the values of posX and posY according to the coordinates where the user clicked and the canvas width and height, accordingly:

Final adjustments

Although now we have a working 3d model with interactive positions based on clicks, when trying out our program, we would get something like this:

As we can see, the cube isn’t moving entirely to the specific location we want it to. This is because the cube is moving according to a distance, and we have the z coordinate set to -6, so the cube doesn’t move entirely to the position of x and y. So how do we solve this? We simply need to do some multiplications of the posX and posY factors in the translation of the cube, so we can start playing around with the numbers and find out where does the movement of the cube feels more natural. We got 5 for the factor of posX and 2 for posY:

Finally, we can see our full example working interactively:

Planned vs Estimated hours

Personally I estimated 2 hours for doing this exercise but got it done in 3, because of the missunderstanding of some issues with the movement of the cube in the last part. Now, knowing how everything works, I estimate I could make it work in a matter of minutes without any problem at all. This demostrates the simplicity of doing cool and interactive examples in WebGL

--

--