Advertisement
RCAProduction

HTML5 Relative Dual Animation

Dec 11th, 2013
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <style>
  5. body {
  6. margin: 0px;
  7. padding: 0px;
  8. }
  9. </style>
  10. </head>
  11. <body>
  12. <canvas id="myCanvas" width="578" height="200"></canvas>
  13. <script>
  14. window.requestAnimFrame = (function(callback) {
  15. return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
  16. function(callback) {
  17. window.setTimeout(callback, 1000 / 60);
  18. };
  19. })();
  20.  
  21. function moveSquare(mySquare, newX, newY) {
  22. mySquare.x = mySquare.x + newX;
  23. mySquare.y += newY;
  24.  
  25. }
  26.  
  27.  
  28.  
  29. function drawRectangle(myRectangle, mySquare, context) {
  30. //context.beginPath();
  31. context.fillStyle = 'rgb(0,0,255)';
  32. context.fillRect(mySquare.x, mySquare.y, mySquare.width, mySquare.height);
  33. context.fillStyle = 'rgba(255,0,0,0.5)';
  34. context.fillRect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
  35. context.fill();
  36. context.lineWidth = myRectangle.borderWidth;
  37. context.strokeStyle = 'black';
  38. context.stroke();
  39. }
  40. function animate(myRectangle, mySquare, canvas, context, startTime) {
  41. // update
  42. var time = (new Date()).getTime() - startTime;
  43.  
  44. var linearSpeed = 100;
  45. // pixels / second
  46. var newX = linearSpeed * time / 1000;
  47.  
  48. if(newX < canvas.width - myRectangle.width - myRectangle.borderWidth / 2) {
  49. myRectangle.x = newX;
  50. }
  51. if(mySquare.x < myRectangle.x - mySquare.width) {
  52. moveSquare(mySquare, .75, 0);
  53. }
  54.  
  55.  
  56.  
  57.  
  58. // clear
  59. context.clearRect(0, 0, canvas.width, canvas.height);
  60.  
  61. drawRectangle(myRectangle, mySquare, context);
  62.  
  63. // request new frame
  64. requestAnimFrame(function() {
  65. animate(myRectangle, mySquare, canvas, context, startTime);
  66. });
  67. }
  68. var canvas = document.getElementById('myCanvas');
  69. var context = canvas.getContext('2d');
  70.  
  71. var myRectangle = {
  72. x: 0,
  73. y: 75,
  74. width: 100,
  75. height: 50,
  76. borderWidth: 5
  77. };
  78.  
  79. var mySquare = {
  80. x:200,
  81. y:75,
  82. width: 50,
  83. height: 50,
  84. borderWidth: 5
  85. }
  86.  
  87.  
  88. var startTime = (new Date()).getTime();
  89. //r go = true;
  90. // while(go) {
  91. animate(myRectangle, mySquare, canvas, context, startTime);
  92. // }
  93.  
  94. // wait one second before starting animation
  95.  
  96. </script>
  97. </body>
  98. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement