Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE HTML>
- <html>
- <head>
- <style>
- body {
- margin: 0px;
- padding: 0px;
- }
- </style>
- </head>
- <body>
- <canvas id="myCanvas" width="578" height="200"></canvas>
- <script>
- window.requestAnimFrame = (function(callback) {
- return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
- function(callback) {
- window.setTimeout(callback, 1000 / 60);
- };
- })();
- function moveSquare(mySquare, newX, newY) {
- mySquare.x = mySquare.x + newX;
- mySquare.y += newY;
- }
- function drawRectangle(myRectangle, mySquare, context) {
- //context.beginPath();
- context.fillStyle = 'rgb(0,0,255)';
- context.fillRect(mySquare.x, mySquare.y, mySquare.width, mySquare.height);
- context.fillStyle = 'rgba(255,0,0,0.5)';
- context.fillRect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
- context.fill();
- context.lineWidth = myRectangle.borderWidth;
- context.strokeStyle = 'black';
- context.stroke();
- }
- function animate(myRectangle, mySquare, canvas, context, startTime) {
- // update
- var time = (new Date()).getTime() - startTime;
- var linearSpeed = 100;
- // pixels / second
- var newX = linearSpeed * time / 1000;
- if(newX < canvas.width - myRectangle.width - myRectangle.borderWidth / 2) {
- myRectangle.x = newX;
- }
- if(mySquare.x < myRectangle.x - mySquare.width) {
- moveSquare(mySquare, .75, 0);
- }
- // clear
- context.clearRect(0, 0, canvas.width, canvas.height);
- drawRectangle(myRectangle, mySquare, context);
- // request new frame
- requestAnimFrame(function() {
- animate(myRectangle, mySquare, canvas, context, startTime);
- });
- }
- var canvas = document.getElementById('myCanvas');
- var context = canvas.getContext('2d');
- var myRectangle = {
- x: 0,
- y: 75,
- width: 100,
- height: 50,
- borderWidth: 5
- };
- var mySquare = {
- x:200,
- y:75,
- width: 50,
- height: 50,
- borderWidth: 5
- }
- var startTime = (new Date()).getTime();
- //r go = true;
- // while(go) {
- animate(myRectangle, mySquare, canvas, context, startTime);
- // }
- // wait one second before starting animation
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement