Flying memes

A mouse driven CSS3 ‘rotate3d’ parallax gallery for Safari

I’m recently enjoying KillZone 2 so much; during one of my gaming sessions I noticed that the loading screen is designed as a bas-relief that you can partially rotate using the joypad oscilloscope, this technique, although easy to implement in a PS3 game, produce a very interesting effect and so I decided to try to transpose it to a web gallery.

To archive such effect I used CSS3 3d properties, in particular the ‘rotate3d‘ one; here’s the portion of html used to define the picture: three divs have been used as layers with ‘preserve3d’ and ‘translateZ’ to specify the distance between each of them:

<div style="position: absolute; top: 50%; left:50%; margin-left: -350px; margin-top: -233px;
            -webkit-perspective: 1000;" >
  <div id="picture" style="height: 466px;
          width: 699px;
          -webkit-transform-style: preserve-3d;
          background: url('flowers.png') no-repeat;
          ">
          <div style="width: 377px;
                height: 424px; background: url('body.png') no-repeat;
                position: absolute;
                -webkit-transform: translateZ(20px);
                top: 45px; left: 75px;">
          </div>
          <div style="position: absolute;
          -webkit-transform: translateZ(30px);
          bottom: 0px; right: 0px; padding-left: 30px; padding-right: 30px;
          background: rgba(0,0,0,0.6);     font-family: 'Lobster', arial, serif;
          color: #FFF; font-size: 30px; line-height: 60px; text-align:center;">
            Francy taking pictures
          </div>
  </div>
</div>

Next I wrote a small JQuery flavored Javascript to rotate the ‘layer0’ div according to mouse position; the other two divs follows the rotation of the first automatically preserving the 3D spatial relations.

$(document).ready(function() {
    $('body').mousemove(function(event) {
        cx = Math.ceil($('body').width() / 2.0);
        cy = Math.ceil($('body').height() / 2.0);
        dx = event.pageX - cx;
        dy = event.pageY - cy;

        tiltx = (dy / cy);
        tilty = - (dx / cx);
        radius = Math.sqrt(Math.pow(tiltx,2) + Math.pow(tilty,2));
        degree = (radius * 20);

        $('#picture').css('-webkit-transform','rotate3d(' + tiltx + ', ' + tilty + ', 0, ' + degree + 'deg)');
    });
});

And that’s all; you can try the demo at this link: Parallax Gallery, please note that only works on Safari; here’s a screenshot of the effect in action:

Tags: , , ,