WebGL enhanced drag slider tutorial with curtains.js (part 1)
The slider will be written in three parts. In the first part, we’ll write a Slider class that will create a neat responsive drag slider. In the second part, we’ll extend it to add the WebGL effect. In the third and final part, we’ll learn how to improve the overall performance by removing all unnecessary reflow or layout calls.
We can easily see the advantages of using curtains.js:
- Clean and SEO friendly HTML code
- You don’t have to worry about the sizes and positions of your WebGL objects
- Most of the stuff (like resize) will be handled under the hood by the library.
- In any case, if there’s an error during the WebGL initialization or in your shaders, the slider will still work!
This is what we’ll have at the end of the first part:
Part 1. HTML & CSS
The CSS is also really easy. Our #planes div uses flexbox to display its children. We set the width in landscape mode based on the width of the slides and their number. On portrait mode, we reset its width and change the flex direction to column.
We’ll add a few CSS properties during drag, preventing text selection and some animations.
Now let’s build our slider.
All in all, there are three steps in this slider:
- On mouse down, we’ll start dragging our slider and get our drag start position. The slider starts translating.
- On mouse up we’ll get our mouse drag end position to use for next drag. Note that the slider is still translating until our linear interpolation is complete.
- We will continuously interpolate the position of our slider between its current translation and our mouse drag movement position. We’ll set up a request animation frame loop to handle that.
We’ll start by creating a Slider class that handles our slider and init its variables.
We write three helper functions to interpolate values, retrieve mouse and touch positions, and set the slider direction and boundaries. Then we add a few hooks — these will be useful later when we extend the Slider class to add the WebGL part:
Next, we take care of the animation and translation. We use a request animation frame loop to update the slider translation at each tick and set up the required hooks.
In the next part, we’re going to write the methods that bind to the event listeners. This is where we’re going to write the three main steps we’ve already seen. We’ll also add a method to be called on resize.
OK, we’re almost done with our drag slider.
We just need to create a setup function that will register all our event listeners and start the animation loop. We’ll call it inside our constructor.
We’ll also be creating a function to cleanly destroy our slider, which means removing all event listeners and canceling our request animation frame:
That’s it for now. I hope you liked it so far.
In the next part, we’ll be modifying our HTML and CSS and then adding to the WebGL part by extending our Slider class.