1.01 World Net BoK

WEB ANIMATION: ONE

Add Animations to your Website

Part 1 of our Web Animation Series - JavaScript

Welcome to our Web Animation Series


This is the first episode in a short series on Animation. I have planned three but who knows where we will go once I get started.

It is aimed primarily, at beginners and will cover both JavaScript and CSS animation.

We will start with some simple animations and move on to more practical examples as we progress.

So let's get started with Javascript.
JavaScript Animation as it sounds, uses the JavaScript scripting language to modify the properties of objects within the DOM (Document Object Model).

That may sound technical, but simply put, we will be modifying HTML attributes within a page via the document object.

For example, if we want to change the color of a heading, we would first give the heading an identifier, so we can reference it via document:
<h1 id="heading1">This is a Heading</h1>

Then modify the color property via JavaScript:
<script language="JavaScript">
hHead = document.all('heading1');
if (hHead) hHead.color = 'green';
</script>>
Simples.

Now that we have that sorted, I can tell you that Javascript animation is not much more difficult than that! But, there are three key things that we must get absolutely right:
  • Timing
  • Display Update
  • Positioning

By Display Update, I am refering to the fact that the updates we make to objects must be reflected in what we see. In other words, we must make sure that the browser refreshes our changes.

We can achieve two of these objectives with an internal JavaScript function: setInterval(). This function will call a function, that we create, after a specified number of milli-seconds. And, because it creates a thread for each instance, it solves the Display Update issue.

If you want to know the ins-and-outs of setInterval(), check it out via Google. But for the purposes of this Article, all we need to know is that we will use it to call our animation function at regular intervals and is therefore, the Timing aspect of our animation method.

I will cover Positioning later.

So buckle-up, and we'll get started with an example.

Example Animation 1: Bouncer


There are three parts or Languages that we will be using in the example, that I am sure you are familiar with, or have hear of:
  • HTML
  • CSS
  • JavaScript

Don't worry, it is all simple stuff. The HTML creates the objects, the CSS the styles and the JavaScript the animation.

Let's go through them, one by one.

Example 1: HTML


<div class="container" onclick="toggleBouncer();">
      <div id="Bouncer" class="bouncer">a</div>
</div>


The HTML includes a <div> that contains the animation and the bouncer object with the identifier "Bouncer", that is also a <div>.

The container <div> has on onclick event that calls the JavaScript function toggleBouncer() which in turn, will start and stop the animation.

Example 1: CSS


div.container {
   position: relative;
   background: teal;
   width: 340px; height: 300px;
   font-family: "Monaco", "Courier", "Courier New", "Arial";
   font-style: normal; font-weight: normal; font-size: 1.2rem;
}
div.container:hover {
   cursor: pointer;
}
div.bouncer {
   position: absolute;
   left: 155px; top: 136px;
   background: white; color: black;
   width: 30px; height: 30px;
   text-align: center;
}


An important thing I mentioned previously that must be done is the positioning.

The containing object must have position set to relative and the animation object absolute. This allows absolute positioning relative to the container.
Note: If this is not set correctly, your animation will not work.

Other than that, the rest is straight-forward. One thing to note, the div.container:hover {} section displays a pointer when you hover over the container, just to let you know you can click it.

Example 1: JavaScript


<script language="JavaScript">
// Global variables
var stop = true;
var hIntAnimate;

var x = 155; var y = 136;
var moveX = 2; var moveY = 2;
var containerX = 340; var containerY = 300;
var bouncerX = 30; var bouncerY = 30;
var bump = false;

function animateBouncer() {
   // Get handle to 'Bouncer'
   var hBouncer = document.all('Bouncer');

   if (hBouncer && !stop) {
      // Use setInterval() to time calls to animateMove()
      hIntAnimate = setInterval(animateMove, 10);

      function animateMove() {
         // Movement cycle
         nextX = x + moveX;
         nextY = y + moveY;
         bump = false;

         if (nextX < 0 || nextX + bouncerX > containerX) {
            moveX = (0 - moveX);
            bump = true;
         }

         if (nextY < 0 || nextY + bouncerY > containerY) {
            moveY = (0 - moveY);
            bump = true;
         }

         x += moveX;
         y += moveY;

         // Update 'Bouncer'
         hBouncer.style.left = x + 'px';
         hBouncer.style.top = y + 'px';

         // Bump to another random char?
         if (bump)
            hBouncer.innerHTML = String.fromCharCode((Math.random() * 26) + 97);
      }
   }
}

function toggleBouncer() {
   if (stop) {
      // Start animation
      stop = false;

      animateBouncer();
   } else {
      // Stop animation and clear setInterval()
      stop = true;

      if (hIntAnimate)
         clearInterval(hIntAnimate);
   }
}
</script>


Ok, so this is where the animation is done and is a little more complicated. But not too bad if we just go through what each section does.

Global variables


These variables are available to all the JavaScript code within the entire page. This allows the animations to be stopped and started while remembering their previous state.

They contain:
  • Stop/start status
  • Handle to setInterval() object
  • Various positions, sizes and movement increments

Note: We could get the positioning and sizing from the objects themselves but for the purposes of this Article let's keep it simple.

Bouncer Handle


This is simply a handle to the bouncer object so we can update its properties.

setInterval Object/Handle


As explained above setInterval() is the timing aspect of our animation and regulary calls the animateMove() function.

animateMove()


This function performs one cycle of the animation by updating the properties of hBouncer.

By calling it at regular intervals we achieve animation.

toggleBouncer()


This function starts and stops the animation:
  • Calling animateBouncer() to start
  • Setting stop to true (and clearing the setInterval() object) to stop

And that's it.

Try the interactive example below ...

Interactive Example: Bouncer


Click on the teal container to start the animation - click again to stop.

a

Example Animation 2: Squish


Our second example is fairly similar to the first but also introduces color animation.

It is really just included in the Article because I though it was a fun animation example.

PLEASE NOTE:
Most style, function and variable names in this example have been suffixed with X so they won't clash with the first example.

Example 2: HTML


<div class="containerX" onclick="toggleSquish();">
      <div id="Squish" class="squish"></div>
</div>

Example 2: CSS


div.containerX {
   position: relative;
   background: silver;
   width: 300px; height: 300px;
}
div.containerX:hover {
   cursor: pointer;
}
div.squish {
   position: absolute;
   left: 100px; top: 100px;
   background: red;
   width: 100px; height: 100px;
   text-align: center;
}

Example 2: JavaScript


<script language="JavaScript">
// Global variables
var stopX = true;
var hIntAnimateX;

var xx = 100; var yy = 100;
var realXX = xx; var realYY = yy;
var moveAmt = 1;
var containerXX = 300;
var squishXX = 100; var squishYY = 100;
var sizeXX = squishXX; var sizeYY = squishYY;
var squishMax = 80;

var r = 255; var g = 0; var b = -255;
var rX = 2; var gX = 0.5; var bX = 1;

function animateSquish() {
   // Get handle to 'Squish'
   var hSquish = document.all('Squish');

   if (hSquish && !stopX) {
      // Use setInterval() to time calls to animateMoveX()
      hIntAnimateX = setInterval(animateMoveX, 5);

      function animateMoveX() {
         // Movement cycle
         if (xx < 0-squishMax) {
            moveAmt = (0 - moveAmt);
         } else if (xx+squishXX > containerXX+squishMax) {
            moveAmt = (0 - moveAmt);
            xx += moveAmt;
         } else if (xx < 0) {
            sizeXX += moveAmt;
            realYY += moveAmt / 2;
            sizeYY -= moveAmt;
         } else if (xx+squishXX > containerXX) {
            realXX = xx;
            sizeXX -= moveAmt;
            realYY -= moveAmt / 2;
            sizeYY += moveAmt;
         } else if (sizeXX <= squishXX) {
            realXX = xx;
            sizeXX = squishXX;
            realYY = yy;
            sizeYY = squishYY
         } else {
            realXX = xx;
         }

         xx += moveAmt;

         // Color cycle
         if (r <= -256 || r >= 512)
            rX = 0 - rX;
         if (g <= -256 || g >= 512)
            gX = 0 - gX;
         if (b <= -256 || b >= 512)
            bX = 0 - bX;

         r += rX;
         g += gX;
         b += bX;

         // Update 'Squish'
         hSquish.style.left = realXX + 'px';
         hSquish.style.top = realYY + 'px';
         hSquish.style.width = sizeXX + 'px';
         hSquish.style.height = sizeYY + 'px';
         hSquish.style.background = 'rgb(' + r + ',' + g + ',' + b + ')';
      }
   }
}

function toggleSquish() {
   if (stopX) {
      // Start animation
      stopX = false;

      animateSquish();
   } else {
      // Stop animation and clear setInterval()
      stopX = true;

      if (hIntAnimateX)
         clearInterval(hIntAnimateX);
   }
}
</script>


This is very similar to the first example, although the animation code in animateMoveX() is a little more complicated.

The color animation is achived by simply cycling through RGB values to make-up a semi-random color.

Try the interactive example below ...

Interactive Example: Squish


Click on the silver container to start the animation,
click again to stop.

Conclusion


Well that's it for Part 1, I hope you have found it informative and fun.

Part 2 will tackle CSS Animation and will contain some practical examples. So keep an eye peeled for that one.

If you have any comments, questions or criticisms please contact us here.
John Berry - Nov 2020
John Berry is a Software Engineer with over 25 years experience in Net Technology and our resident CSS expert.
© 2023 www.101world.net ℗ 2023 www.101world.net

The BoK ... brought to you by 1.01 World Net

The BoK is a Book, a Body of Knowledge,
a collection of Articles, a Knowledge Base
of interesting and useful Information.


Processing - please wait...