Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- Using HTML and CSS make a plain white web page that has a 100x100 pixel blue square on it.
- Position the square along the left side of the page, 50 pixels from the top.
- Using javascript animate this square so that it moves 10 pixels right and 10 pixels down per second.
- When the box hits or goes over an edge of the window, change the direction for the related axis.
- </title>
- <style>
- .box{
- width:100px;
- height:100px;
- position: absolute;
- }
- .blue{
- background:#00f;
- }
- .position{
- margin-top: 50px;
- }
- </style>
- </head>
- <body>
- <div class="box blue position" id="move_box"> </div>
- <script>
- var box = document.getElementById('move_box'),
- boxPos = 0,
- boxLastPos = 0,
- boxVelocity = 0.01,
- limit = 300,
- lastFrameTimeMs = 0,
- maxFPS = 60,
- delta = 0,
- timestep = 1000 / 60,
- fps = 60,
- framesThisSecond = 0,
- lastFpsUpdate = 0,
- running = false,
- started = false,
- frameID = 0;
- function update(delta) {
- boxLastPos = boxPos;
- boxPos += boxVelocity * delta;
- // Switch directions if we go too far
- if (boxPos >= limit || boxPos <= 0) boxVelocity = -boxVelocity;
- }
- function draw(interp) {
- box.style.left = (boxLastPos + (boxPos - boxLastPos) * interp) + 'px';
- box.style.top = (boxLastPos + (boxPos - boxLastPos) * interp) + 'px';
- console.log(box.style.top);
- }
- function panic() {
- delta = 0;
- }
- function begin() {
- }
- function end(fps) {
- /*box.style.backgroundColor = 'blue';*/
- }
- function stop() {
- running = false;
- started = false;
- cancelAnimationFrame(frameID);
- }
- function start() {
- if (!started) {
- started = true;
- frameID = requestAnimationFrame(function(timestamp) {
- draw(1);
- running = true;
- lastFrameTimeMs = timestamp;
- lastFpsUpdate = timestamp;
- framesThisSecond = 0;
- frameID = requestAnimationFrame(mainLoop);
- });
- }
- }
- function mainLoop(timestamp) {
- // Throttle the frame rate.
- if (timestamp < lastFrameTimeMs + (1000 / maxFPS)) {
- frameID = requestAnimationFrame(mainLoop);
- return;
- }
- delta += timestamp - lastFrameTimeMs;
- lastFrameTimeMs = timestamp;
- begin(timestamp, delta);
- if (timestamp > lastFpsUpdate + 1000) {
- fps = 0.25 * framesThisSecond + 0.75 * fps;
- lastFpsUpdate = timestamp;
- framesThisSecond = 0;
- }
- framesThisSecond++;
- var numUpdateSteps = 0;
- while (delta >= timestep) {
- update(timestep);
- delta -= timestep;
- if (++numUpdateSteps >= 240) {
- panic();
- break;
- }
- }
- draw(delta / timestep);
- end(fps);
- frameID = requestAnimationFrame(mainLoop);
- }
- start();
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment