Layers Part 5 - Animated Clipping Layers

Animated clipping layers using JavaScript and the DOM.

In the previous part of this series on dynamic layers, I discussed the basic concepts behind clipping layers using Cascading Style Sheets (CSS). While CSS styles form the basis of the animated demo you see on the right, CSS in itself is incapable of producing such an effect. In order to make the effect dynamic, we must employ a combination of JavaScript and the Document Object Model (DOM). Lets begin by looking at the script used in the demonstration:

The Script

<script language="JavaScript">
// animated clipping layer effect
 
clipTop = 0;
clipRight = 200;
clipLeft = 200;
clipBottom = 200;
timer = null;
 
function setClip() {
    clipLayer = document.getElementById('clipLay').style;
    clipLayer.clip.top = clipTop;
    clipLayer.clip.right = clipRight;
    clipLayer.clip.left = clipLeft;
    clipLayer.clip.bottom = clipBottom;
 
    if(clipRight < 400) {
        clipRight += 5; //set the increment values here...
        clipLeft -= 5; //...and here for horizontal clipping!
        clipLayer.clip = 'rect('+clipTop+','+clipRight+','+clipBottom+','+clipLeft+')';
        setTimeout('setClip()', 10);
    }
}
</script>

This script can clip a layer on the horizontal axis or the vertical axis, or even both (although I've yet to try that!). The four variables at the top of the script, clipTop, clipRight etc., set the initial values for the layer's clipping plane. Once again with clipping, the difficulty lies in conceptualising what is going on; the layer is effectively being split vertically in the middle (200 is the center of the 400px layer), and gradually being displayed outwards towards it's left edge (a clip value of 0px) and it's right edge (a clip value of 400px).

if(clipRight < 400) {

The if-statement begins by asking "is the right-clip value less than 400?", and if it is then both it and the left-clip value are incremented by 5 pixels towards the layers edges at 0px and 400px. This pixel increment value can be increased to speed up the animation, or vice versa to slow it down.

To switch the script to vertical clipping, change the above if-statement to look at the clipBottom value, which would start at half the height of the layer and increment to the layer's full height, and set the four initial values as follows:

clipTop = 100;
clipRight = 400;
clipLeft = 0;
clipBottom = 100;

And the if-statement would now look like this:

if(clipBottom < 200) {
    clipTop -= 5;
    clipBottom += 5;
    clipLayer.clip = 'rect('+clipTop+','+clipRight+','+clipBottom+','+clipLeft+')';
    setTimeout('setClip()', 10);
}

Try it and see what difference it makes!

John Collins

I have been writing about web technology and software development since 2001. I am the developer of the Alpha Framework for PHP, and the five.today personal productivity app. I love open source, technology, and economics.