Home › Category Archives › Javascript

Javascript and CSS3 Fun – Rotating the Screen

Info for Nerds (ie: How to rotate the browser’s display)

See http://dotslash.ca/javascript-fun-what-my-browser-looks-like-on-a-boat/ for the example/demo.

Through the magic of CSS2 and some basic Javascript, this is actually pretty simple! Here’s the basic description of the code:

  1. Set up a global variable for the document body’s style element, as well as for a few other things like "angle"
  2. Check to see if we’re on the page that is only showing this post so we don’t mess up the home page when a blurb of this page is shown. (I just did it a quick and dirty way by checking if the page’s title matches this page’s title)
  3. Increase the angle but a small random amount, and if the angle is more than twice PI (in Radians) subract twice PI
  4. Use the sine of the angle divided by a somewhat arbitrary factor to adjust the CSS3 transform’s "rotate()" parameter. (If I didn’t divided it down by the factor it would spin all the way around, just like Google search does when you type “do a barrel roll” in the search!)
  5. Set a timer to do it again in a moment

The Code

<script lang="javascript">
var pi = Math.PI;
var timer;
var factor = 20;
var angle = 0;
var docBody = document.getElementsByTagName("body")[0];
var s = docBody.style;
function stopTimer()
    document.getElementById('stopTimerButton').style.display = "none";
    document.getElementById('straightenUp').style.display = "block";
function rollit()
    angle += Math.random() / 5;
    if (angle > pi)
        angle -= (2 * pi);
    s.transform = "rotate(" + (Math.sin(angle) / factor) + "rad)";
    timer = setTimeout("rollit()", 35);
if (document.title.indexOf('Javascript fun') === -1)
    document.getElementById("viewThisPost").style.display = "block";
    document.getElementById("stopTimerButton").style.display = "none";
    s.transform = "rotate(" + angle + "rad)";

I haven’t tested this on any browsers other than Firefox… but it’s pretty cool, huh?

Share Button

Javascript fun: What my browser looks like on my boat.

Note: If you’re using Internet Explorer or a mobile device this may not work… try Firefox!

Info for Nerds (ie: How it’s done) is in the next post

Share Button