Build an interactive 3D rotating carousel, using CSS 3D transformation and JavaScript to enhance the dynamic display of web images or content. This article will guide you step by step how to create this component.
When I first studied this topic, I did not need a 3D carousel, but paid more attention to its specific implementation details. The core technology is of course from CSS Transforms Module Level 1, but in the process, many other front-end development technologies will be applied, involving all aspects of CSS, Sass and client JavaScript.
This CodePen shows different versions of components and I will show you how to build them.
To illustrate the settings for CSS 3D conversion, I will show you the pure CSS version of the component. I'll then show you how to enhance it using JavaScript to develop a simple component script.
Key Points
Character chart mark
For markup, the image inside the component is wrapped in a <figure></figure>
element, which provides a basic framework:
<div class="carousel"> <figure> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> ... <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> </figure> </div>
This will be our starting point.
Geometric Structure of Carousel Figure
Before looking at CSS, let's outline the plans that will be developed in the following sections.
<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173967151412585.jpg" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /></p>
<p> Therefore, the number of sides of this polygon is the same as the number of images in the carousel diagram: the polygons of three images are equilateral triangles; four images are squares; five are pentagons; etc.: </p>
<p>What if there are fewer than three images in the carousel? The polygon cannot be defined and the following process cannot be applied as is. In any case, it is quite useless to have only one image; two images are slightly more likely, and they can be placed on two points opposite in the circle with diameters. For simplicity, these special cases are not handled and assume that there are at least three images. However, the relevant code modification is not difficult. </p><p>This imaginary reference polygon will be located in 3D space, perpendicular to the plane of the viewport, and push its center back towards the screen, the distance equals its center distance (the distance from one edge of the polygon to its center), as shown in the figure below Show: </p>
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173967151540038.jpg" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /></p>
<p> In this way, the current viewer-oriented edge will be at screen plane z = 0, while the front image will not be affected by perspective shortening and will have its normal 2D size. The letter d in the picture represents the value of the CSS perspective attribute. </p>
<p><strong>Construct the carousel graph geometric structure</strong></p>
<p> In this section, I will show you the key CSS rules, which I will explain step by step. </p>
<p> In the following code snippet, use some Sass variables to make the component easier to configure. I will use <code>$n
to represent the number of images in the carousel and use $item-width
to specify the width of the image.
<figure>
element is the inclusion box of the first image and is also the reference element around which other images are positioned and transformed. Assuming that the carousel now has only one image to show, I can start with size and alignment:
<div class="carousel"> <figure> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> ... <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> </figure> </div>
<figure>
elements have a prescribed carousel item width and have the same height as the image (they can have different sizes, but must have the same aspect ratio). In this way, the carousel container height will be automatically adjusted according to the image height. Also, <figure>
is horizontally centered in the carousel container.
The first image does not require additional conversion because it is already in its target position, i.e. the front of the carousel.
Can rotate the carousel in 3D space by applying a rotation transformation to the <figure>
element. This rotation must be around the center of the polygon, so I will change the default transform-origin of <figure>
:
.carousel { display: flex; flex-direction: column; align-items: center; > * { flex: 0 0 auto; } .figure { width: $item-width; transform-style: preserve-3d; img { width: 100%; &:not(:first-of-type) { display: none /* Just for now */ } } } }
This value is inverse because in CSS the positive direction of the z-axis is to leave the screen and face the viewer. Brackets are required to avoid Sass syntax errors. The calculation of the polygon paracentric distance will be explained later.
After converting the reference system of the <figure>
element, the entire carousel can be rotated by its (new) y-axis rotation:
.carousel figure { transform-origin: 50% 50% (-$apothem); }
I will return the details of this rotation later.
Let's continue to convert other images. Using absolute positioning, images are stacked inside <figure>
:
.carousel figure { transform: rotateY(/* some amount here */rad); }
z-index value is ignored because this is only a preliminary step in subsequent conversion. In fact, each image can now rotate an angle around the y-axis of the carousel image, which depends on the polygonal edges of the assigned image. First, like the <figure>
element, modify the image's default transform-origin and move it to the center of the polygon:
<div class="carousel"> <figure> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> ... <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> </figure> </div>
The image can then rotate a quantity about its new y-axis, which is given by ($i - 1) * $theta
radians, where $i
is the index of the image (starting from 1), $theta = 2 * $PI / $n
, where $PI
means The mathematical constant π. So the second image will rotate $theta
, the third one will rotate 2 * $theta
, and so on until the last image will rotate ($n - 1) * $theta
.
Due to the hierarchical nature of nested CSS transformations, this relative arrangement of images will be preserved during carousel map rotation (i.e., rotation about the modified y-axis of <figure>
).
The amount of rotation of this image can be assigned using the Sass @for
control command:
.carousel { display: flex; flex-direction: column; align-items: center; > * { flex: 0 0 auto; } .figure { width: $item-width; transform-style: preserve-3d; img { width: 100%; &:not(:first-of-type) { display: none /* Just for now */ } } } }
This is to use the for...through
structure instead of for...to
, because for for...to
, the last value assigned to the index variable $i
will be n-1 instead of n.
Note two instances of Sass' #{}
interpolation syntax. In the first instance, it is used for indexing the :nth-child()
selector; in the second instance, it is used to set the rotation property value.
Calculate the paracentric distance
The calculation of the paracentric distance of the polygon depends on the number of edges and the width of the edges, i.e., the $n
and $item-width
variables. The formula is:
.carousel figure { transform-origin: 50% 50% (-$apothem); }
where tan()
is the tangent trigonometric function.
This formula can be derived through some geometry and trigonometry. In the pen's source code, this formula is not implemented as is because the tangent function is not available in Sass, so hardcoded values are used. Instead, the formula will be fully implemented in a JavaScript demonstration.
Interval carousel item
At this point, the carousel images are "stitched" side by side to form the desired polygon shape. But here, they are tightly stacked together, and in a 3D carousel, there is usually space between them. This distance enhances perception of 3D space as it allows you to see an image with the back facing back of the carousel.
This gap between images can optionally be added by introducing another configuration variable $item-separation
and using it as a horizontal fill for each <img alt="Building a 3D Rotating Carousel with CSS and JavaScript" >
element. More precisely, take half of this value as left and right fill:
.carousel figure { transform: rotateY(/* some amount here */rad); }
The final result can be seen in the following demonstration: (The CodePen link should be inserted here to show the interval carousel item)
The image becomes translucent using the opacity
attribute to better illustrate the carousel structure, and the flex layout on the carousel root element is used to center it vertically in the viewport.
Rotation carousel picture
To facilitate test carousel image rotation, I will add a UI control to navigate back and forth between images. (The CodePen link should be inserted here to display the rotating carousel image)
We use a currImage
integer variable to indicate which image is in front of the carousel. This variable increases or decreases by one unit when the user interacts with the previous/next button.
Update currImage
, the carousel image rotation will be performed in the following ways:
<div class="carousel"> <figure> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> ... <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> </figure> </div>
(Here and in the following code snippet, insert expressions into strings using ES6 template literals; if you prefer, you can use the traditional "" concatenation operator)
where theta
is the same as before:
.carousel { display: flex; flex-direction: column; align-items: center; > * { flex: 0 0 auto; } .figure { width: $item-width; transform-style: preserve-3d; img { width: 100%; &:not(:first-of-type) { display: none /* Just for now */ } } } }
Rotation is -theta
because to navigate to the next item, a counterclockwise rotation is required and this rotation value is negative in the CSS conversion.
Please note that the currImage
value is not limited to the [0, numImages – 1]
range, but can grow infinitely, both in positive and negative directions. In fact, if the front image is the last (so currImage == n-1
) and the user clicks the next button, if we reset currImage
to 0 before the first carousel image, the rotation angle will be from (n-1)*theta
converts to 0, which will rotate the carousel in the opposite direction on all previous images. A similar problem occurs when the previous button is clicked if the front image is the first one.
To be picky, I should even check for potential overflows of currentImage
, because the Number
data type cannot take arbitrarily large values. These checks are not implemented in the demo code.
Enhanced with JavaScript
After seeing the basic CSS that forms the core of the carousel graph, it is now possible to enhance components in a variety of ways using JavaScript, such as:
First, I remove variables and rules related to converting origin and rotation from the stylesheet, as these will be done using JavaScript: (Updated CSS code should be inserted here)
Next, the carousel()
function in the script is responsible for initializing the instance:
.carousel figure { transform-origin: 50% 50% (-$apothem); }
root
parameter refers to the DOM element that saves the carousel diagram.
Usually, this function will be a constructor that generates an object for each carousel graph on the page, but here I don't write a carousel library, so a simple function will suffice.
To instantiate multiple components on the same page, the code waits for all images to load, registers the listener for the window
event for the load
object, and then calls carousel
for each element with the carousel()
class
.carousel figure { transform: rotateY(/* some amount here */rad); }
carousel()
Before checking the conversion settings code, I will cover some key variables and how to initialize them based on the instance configuration:
<div class="carousel"> <figure> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> ... <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Building a 3D Rotating Carousel with CSS and JavaScript " /> </figure> </div>
Number of images (n) is initialized according to the number of child elements of <figure>
element. The spacing between slides (gap) is initialized from the HTML5 data-gap
property (if set). The back visibility flag (bfc) is read using HTML5's dataset
API. This will be used later to determine whether the image on the back of the carousel is visible.
Set CSS conversion
The code for setting CSS conversion related attributes is encapsulated in setupCarousel()
. This nested function has two parameters. The first is the number of items in the carousel graph, that is, the n variables introduced above. The second parameter s is the side length of the carousel polygon. As I mentioned earlier, this is equal to the width of the image, so you can read the current width of one of them using getComputedStyle()
:
.carousel { display: flex; flex-direction: column; align-items: center; > * { flex: 0 0 auto; } .figure { width: $item-width; transform-style: preserve-3d; img { width: 100%; &:not(:first-of-type) { display: none /* Just for now */ } } } }
In this way, the image width can be set using the percentage value.
To keep the carousel graph adaptive, I registered a listener for the window resizing event, which again calls with (possibly modified) image size setupCarousel()
:
.carousel figure { transform-origin: 50% 50% (-$apothem); }
For simplicity, I did not de-jitter resize listener.
setupCarousel()
The first thing I do is to calculate the paracentric distance of a polygon using the passed parameters and the formula discussed earlier:
.carousel figure { transform: rotateY(/* some amount here */rad); }
This value is then used to modify the <figure>
of the transform-origin
element to obtain the new rotation axis of the carousel:
.carousel figure img:not(:first-of-type) { position: absolute; left: 0; top: 0; }
Next, apply the image style:
.img:not(:first-of-type) { transform-origin: 50% 50% (-$apothem); }
The first loop allocates padding for space between carousel items. The second loop sets up the 3D conversion. The last loop handles the back side if the relevant flag is specified in the carousel diagram configuration.
Finally, call rotateCarousel()
to move the current image to the front. This is a small helper function, given the index of the image to be displayed, it rotates the <figure>
element about its y-axis to move the target image to the front. The navigation code also uses it to move back and forth:
.carousel figure img { @for $i from 2 through $n { &:nth-child(#{$i}) { transform: rotateY(#{($i - 1) * $theta}rad); } } }
This is the final result, a demonstration where several carousels are instantiated, each with a different configuration: (The final CodePen link should be inserted here)
Source and Conclusion
Before the end, I just want to thank some sources for researching this tutorial: (reference sources should be listed here)
If you have any questions or comments about the function of the code or carousel diagram, please feel free to leave a message below.
FAQ on building 3D rotary carousel diagrams with CSS and JavaScript
Adapting your 3D rotating carousel graphs involves using media queries in CSS. Media queries allow you to apply different styles to different devices according to the screen size of your device. You can adjust the size and position of the carousel graph elements to suit smaller screens. Also consider touch events on mobile devices, as they do not have a hover state like desktop computers.
Yes, you can add more slides to the carousel. In the HTML structure, you can add more list items in an unordered list. Each list item represents a slide. Remember to adjust the rotation angle of each slide in CSS to correctly position them in 3D space.
You can add navigation buttons to carousel diagrams using HTML and JavaScript. In your HTML, add two buttons for the previous and next navigation. In your JavaScript, add event listeners to these buttons. When clicked, they should update the rotation of the carousel to display the previous or next slide.
Of course, you can use images as slideshows. Instead of setting background colors in CSS, you can set background images for each slide. Make sure the image has the correct size and resolution for the best visual effect.
Autoplay can be added using JavaScript. You can use the setInterval
function to automatically update the rotation of the carousel diagram after a period of time. Remember to clear the intervals when the user interacts with the carousel to prevent unexpected behavior.
Yes, you can add transition effects to the carousel using CSS. The transition
property allows you to animation changes in CSS properties over a specified duration. You can apply it to the transform
attribute to animate the rotation of the carousel map.
Making the carousel graph infinite loop involves some JavaScript. When the carousel reaches the last slide, you can reset its rotation to the first slide. This gives people the illusion of infinite loops.
Yes, you can add text on the slide. In your HTML you can add text elements to each list item. In your CSS, locate text elements according to the position of the slide and style them as needed.
CSS can be used to add fade effects. You can use the opacity
attribute in combination with the transition
attribute to animate the fade effect. Adjust the slideshow to position in the carousel to create the desired effect. opacity
Yes, you can use different shapes as carousels. The shape of the carousel graph is determined by the transform
attribute in CSS. By adjusting the value of the transform
property, you can create a carousel of cubes, cylinders, or any other 3D shape.
The above is the detailed content of Building a 3D Rotating Carousel with CSS and JavaScript. For more information, please follow other related articles on the PHP Chinese website!