Advanced Coding Assignment
A ball moving over a checkboard following the clicked location.
by codef0rmer
HTML
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
overflow: hidden;
margin: 0;
padding: 0;
}
#ball {
position: absolute;
width: 48px;
height: 48px;
}
.viewport {
position: absolute;
width: 1000px;
height: 1000px;
background: url(http://i1214.photobucket.com/albums/cc493/ChocoCosmos31/Photoshop/checkerboard6qi.png) center center repeat;
margin-left: auto;
margin-right: auto;
margin-bottom: auto;
margin-top: auto;
}
</style>
</head>
<body>
<div class='viewport'></div>
<img id="ball" src="http://www.rw-designer.com/icon-view/3718.png" />
<script>
function getRotationDegrees(obj) {
var matrix = obj.css("-webkit-transform") ||
obj.css("-moz-transform") ||
obj.css("-ms-transform") ||
obj.css("-o-transform") ||
obj.css("transform"),
angle = 0;
if(matrix !== 'none' && matrix !== undefined) {
var values = matrix.split('(')[1].split(')')[0].split(',');
var a = values[0];
var b = values[1];
angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
} else { angle = 0; }
return angle;
}
// shim layer with setTimeout fallback
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
// Actual code
var $viewport = $('div.viewport'),
viewportWidth = $viewport.width(),
$ball = $('#ball'),
ballWidth = $ball.width(),
currentRotation = getRotationDegrees($ball),
viewportXBoundary = $viewport.position().left + $viewport.width(),
viewportYBoundary = $viewport.position().top + $viewport.height(),
ballPosLeft = ballPosTop = 0;
// Position the...