public
Last active

Scrolling along the Z-Axis

  • Download Gist
zscroll.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
<html>
<head>
<title>Scrolling along the Z-Axis</title>
<!--
Example from http://eng.wealthfront.com/2012/03/scrolling-z-axis-with-css-3d-transforms.html
Assumes browser window is sized at a height of 400px (the size of the black box).
-->
<style>
body{height:600px;}
#viewport {
position:fixed;
-webkit-perspective:100px;
-webkit-perspective-origin:50% 50%;
border: 2px solid black;
height: 400px;
width: 400px;
left:50%;
margin-left:-200px;
}
.box {
position:absolute;
width:100px;
height:100px;
left:50%;
top:50%;
margin-left:-50px;
margin-top:-50px;
}
#a {
background-color:rgba(255,0,0,.5);
border:2px solid red;
-webkit-transform:translateZ(-100px)
 
}
#b {
background-color:rgba(0,255,0,.5);
border:2px solid green;
-webkit-transform:translateZ(-50px)
}
#c {
background-color:rgba(0,0,255,.5);
border:2px solid blue;
-webkit-transform:translateZ(0px)
}
 
</style>
</head>
<body>
<div id="viewport">
<div class="box" id="a"></div>
<div class="box" id="b"></div>
<div class="box" id="c"></div>
</div>
<script>
var scrollPosition = document.body.scrollTop,
boxPositions = [-100, -50, 0];
function scrollDelta() {
var newScrollPosition = document.body.scrollTop,
delta = newScrollPosition - scrollPosition;
scrollPosition = document.body.scrollTop;
return delta;
}
function moveCamera() {
var boxes = document.getElementsByClassName("box"),
delta = scrollDelta();
for (var i=0,l=boxes.length;i<l;i++) {
boxPositions[i] += parseInt(delta);
boxes[i].style["-webkit-transform"] = "translateZ("+boxPositions[i]+"px)";
}
}
window.addEventListener("scroll", moveCamera, false);
</script>
</body>
</html>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.