Monday, 24 February 2014

Filled Under:

Using CSS 3D Effects And Key-Frame Animation

19:43:00


CSS keyframe animation and 3D effects are becoming increasingly popular these days and can be used to create a whole bunch of interesting and cool effects. However, if you’re still trying to rap your head around how they work, then this tutorial is definitely for you!
As with most things web-dev related, the best way to understand something is to use it so you can interactively explore the various functions and other features. In this tutorial we’ll be using a number of CSS effects to create some simple 3D geometry, as well as some basic key-framing to create a series of animations.

The idea with this tutorial, is through following along step-by-step, you’ll see the full scope of using CSS keyframes and 3D effects, at a basic level. I wanted to create a tutorial that used not only one effect, but a number of different effects to give a taste of what CSS is capable of. Once you understand the basics, you can go off and create something really crazy!
That being said, I will not be going through every single step of this tutorial, as that would be way too lengthy and repetitive to be considered productive. Rather, I’ll be explaining the core concepts, you can then dig through the source files to see all the details.
Let’s get started!

Please note, for the purposes of keeping the tutorial mark-up legible and compact, I will be omitting browser prefixes. You will need to add browser prefixes to the CSS animation properties to ensure browser compatibility. Nettuts+ has a great online prefixer you can use here.

Project Setup

Ok, let’s take a look at the project overview and how everything’s going to work at a fundamental level. Here I’ve created a new HTML5 document. In the head, I’ve referenced an external stylesheet for the CSS, as well as jQuery and a JavaScript doc. We’ll be writing all our animations and effects in CSS, the only thing the JavaScript is for, is applying the animations to the various classes when the cube in get’s clicked.


<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>CSS Keyframe and 3D Animation</title>
<link rel="stylesheet" type="text/css" href="css/style.css"> <!-- Styles and Keyframe Animation -->
<script src="js/jquery.min.js"></script><!--jQuery-->
<script type="text/ecmascript" src="js/js.js"></script> <!-- Apply Animations On Click-->
</head>

<body>
<!--Content Here-->
</body>

</html>
 
 
For our CSS, we’ll add a CSS reset, and some basic styling for the page setup. You can download the CSS reset here, it’s not essential, however it’s just a habit I’ve gotten into. Also I’m using a font called Franchise, which you can download here.

/*=============================================
[ CSS Reset ]
==============================================*/
/*
CSS RESET GOES HERE
*/

/*=============================================
[ Page Setup ]
==============================================*/
@font-face {
font-family: 'franchise';
src: url('../fonts/franchise-bold-hinted-webfont.eot');
font-weight: normal;
font-style: normal;

}
* {
box-sizing: border-box
}

html, body {
margin: 0;
width: 100%;
height: 100%;
}
body {
background: #34495e;
font-family:"franchise";
color:#fff;
padding: 30px;
text-align: center;
overflow:hidden;
}
 

Adding The Cube

Ok so the first thing we need to focus on, is creating that little cube that spins. Don’t worry about all the other stuff for now, let’s just go step-by-step. Let’s look at the HTML for the cube:

<section>
<div class="cube">
<div class="front"></div>
<div class="back"></div>
<div class="right"></div>
<div class="left"></div>
<div class="top"></div>
<div class="bottom"></div>
</div>
</section>
 
As you would expect, the cube has 6 sides, which are then wrapped in the “cube” div, which is then wrapped in a “<section>“. The idea is that the section contains the cube, and cube contains all the sides which are transformed into 3D space. This way when it comes time to rotate the it, we only need to spin the “cube” div, rather than all the individual faces.

Styling The Cube

Ok let’s now look at styling the cube. Take a look through everything and I’ll explain it all below.

section {
width: 100px;
height: 100px;
position: fixed;
top: 50%;
left: 50%;
margin-top: -20px;
margin-left: -20px;
opacity:1;
}
.cube {
position: absolute;
width: 100%;
height: 100%;
transform-style: preserve-3d;
animation-name: rotatecube;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
.cube div {
position: absolute;
width: 100%;
height: 100%;
}
.front {transform: rotateY(0deg) translateZ(50px); }
.right {transform: rotateY(90deg) translateZ(50px); }
.left {transform: rotateY(-90deg) translateZ(50px);}
.top {transform: rotateX(90deg) translateZ(50px); }
.bottom {transform: rotateX(-90deg) translateZ(50px);}
.back {transform: rotateX(180deg) translateZ(50px);}
 
Firstly we centered the “<section>” that wraps the cube, to the middle of the screen and set its height and width to 100px. We then set the cube’s dimensions to 100%, so it’s contained within the section wrap. Then the same for the actual sides of the cube. Then we select each side of the cube, rotate it’s face to the given dimension using the CSS “tranform:rotate” property. We then push the sides out 50px (half of the full width/height) to edge of the container in the 3D space. Because the each side has already been rotated, translating the Z axis means it will be moved in that direction.
You’ll also notice that I’ve added a number of animation properties to the cube wrap. This is the basis of CSS animation. The “anamation-name” part refers to a CSS keyframe animation that we’ll be creating next. 3S is the duration of the animation, linear is the animation transition timing, and infinite makes the animation run contentiously.

Spinning The Cube

Spinning the cube is easy, as we noted above, we’ve already nominated our css keyframe animation name and variables. All we need to do now is setup the keyframes.

@keyframes rotatecube {
0% { transform: rotateY( 0 ) rotateX( 0 ) }
100% { transform: rotateY( 360deg ) rotateX( 360deg ) }
}
 
Ok so CSS keyframes work in a percentage of the animation, which is already defined in time on the element. Here we have simply said the animation starts off at 0 rotation, and ends with a 360 rotation along two axies. The key-frame interpolation has already been set to linear, so when the animation loops, there is no difference in speed. If we set the animation’s timing function to “ease“, every time the cube spins it would slow down in rotation speed at the start and the beginning of the animation loop and look weird.

The Text

Ok let’s look at the text. The text is wrapped in div that is simply used to center it in the screen. Then I’ve separated each word into “spans” given them a shared class of “word” for general styling, and then an individual class for separate animations.

<div class="wordwrap">
<span class="word first"> CSS</span>
<span class="word second"> 3D</span>
<span class="word third">effects</span>
<span class="word fourth">and</span>
<span class="word fifth">keyframe</span>
<span class="word sixth">animation</span>
<span class="word seventh">!</span>
</div>
 
 

Animating The Text

By default the text doesn’t get animated until the cube is clicked. This is achieved by creating an animation class, which contains the key frame animation but doesn’t relate to any HTML elements. Then when the cube is clicked, we use JavaScript to add the animation class to each element. We can then control the order of the animation using CSS by delaying when the animation starts.
Here’s an example. Firstly we position the text at where the animation will end and make it invisible using “opacity“.

.word .first {
top: 50px;
left: 0;
font-size: 150px;
opacity:0;
}
 
 
Then we create a class which contains the animation properties. Note “animation-fill-mode:forwards” means the animation element will retain the last keyframe of the animation. The reason we need this, is because the element is hidden by default, but it becomes visible in the keyframe animation. If we didn’t use it, the animation would run and then the text would disappear again once it completed. We’ve also set the timing and the duration of animation.


.word-clicked {
animation-fill-mode:forwards;
transform: translate3d(0px ,0px, 0px);
animation-name: left-top;
animation-iteration-count: 1;
animation-timing-function:ease;
animation-duration:.5s;
}
 
 
Now the keyframes. So firstly we move the element off the screen and rotate it at the same time. Also we’ve increased the font size so it looks as if the the text is moving in 3D space. The reason I’ve used 0% and then 1% is that if I started the animation off straight away at 0%, you would see the text appear at the center of the screen for a split second, then quickly disappear. Finally, in the last keyframe we set the text to it’s default position, font–size and opacity.


@keyframes left-top {
0% { transform: translate3d(-500px, -1000px, 1000px ) rotate(-90deg); font-size:1200px; }
1% { transform: translate3d(-500px, -1000px, 1000px ) rotate(-90deg); font-size:1200px; opacity:1; }
100% { transform: translate3d(0px ,0px 0px ) rotate(0deg); font-size:150px; opacity:1;}
}
 
 

Triggering the Animation

As I said earlier, the animation is triggered when the cube is clicked. Here we use  an event listener to detect when the cube is clicked, then we add the animation class to the text. Finally we remove the class with a delay so that when the animation has finished, the animation class is removed and it can run again if needed.


//Triggers Animation
var run = document.querySelector('#start');
run.addEventListener('click', function () {
$(".first").addClass("text-clicked");
});

//Remove the animation class so the animation can run again
var resetanimation = document.querySelector('#start');
resetanimation.addEventListener('click', function () {
setTimeout(function(){$(".first").removeClass("text-clicked");},7000);

});
 
 
Here I’ve made a list of commonly used CSS animation properties with their respective meanings:
  • animation-name: – Name your @keyframe animation name.
  • animation-duration: – Dictates the duration of the keyframe animation.
  • animation-timing-function: – Set’s the animation start-end interpolation timing.
  • animation-iteration-count: – Defines how many times the animation will run.
  • animation-play-state: - Defines weather the animation is running or paused.
  • animation-direction: – Defines in which direction the animation will run. e.g in reverse.
  • animation-delay: – Defines weather the animation will have delay before it begins.
  • animation-fill-mode: – Defines whether the element retains the end state of animation keyframes.
That’s it for this one. To find out more, download the source files and take a look at how other effects work.

Are you new to CSS keyframe animation? Have you used keyframe animation for any other projects? Let us know in the comments.

2 comments:

  1. thanks for shared wonderful information of giving best information.its more useful and more helpful. great doing keep sharing
    school promotional video uk

    ReplyDelete
  2. Hi to every one, the contents present at this site are
    actually remarkable for people experience, well, keep up the good work fellows.
    GMAT coaching chennai

    ReplyDelete