index.html 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>EaselJS demo: Time based animation</title>
  5. <script src="http://code.createjs.com/easeljs-0.7.0.min.js"></script>
  6. <script>
  7. var cellSize = 50;
  8. var grid = [[]];
  9. for(var i=0; i<100; i++){
  10. grid[i] = [];
  11. for(var j=0; j<100; j++){
  12. grid[i][j] = {
  13. x: cellSize / 2 + i * cellSize,
  14. y: cellSize / 2 + j * cellSize
  15. };
  16. }
  17. }
  18. var stage, circle, snake;
  19. function init() {
  20. stage = new createjs.Stage("demoCanvas");
  21. snake = {};
  22. snake.body = [];
  23. for(var i=0; i<8; i++){
  24. circle = new createjs.Shape();
  25. circle.graphics.beginFill("red").drawCircle(0, 0, 20);
  26. circle.direction = {x: 0, y: 0};
  27. stage.addChild(circle);
  28. snake.body.push(circle);
  29. }
  30. snake.update = function(){
  31. for(var i=this.body.length - 1; i>0; i--){
  32. this.body[i].x = this.body[i-1].x;
  33. this.body[i].y = this.body[i-1].y;
  34. this.body[i].direction.x = this.body[i-1].direction.x;
  35. this.body[i].direction.y = this.body[i-1].direction.y;
  36. }
  37. };
  38. createjs.Ticker.on("tick", tick);
  39. createjs.Ticker.setFPS(20);
  40. stage.on("stagemousedown", function(evt){
  41. Math.abs(evt.stageX - snake.body[0].x) > Math.abs(evt.stageY - snake.body[0].y) ?
  42. function(){
  43. snake.body[0].direction.x = evt.stageX > snake.body[0].x ? 1 : -1;
  44. snake.body[0].direction.y = 0;
  45. }() : function(){
  46. snake.body[0].direction.y = evt.stageY > snake.body[0].y ? 1 : -1;
  47. snake.body[0].direction.x = 0;
  48. }();
  49. });
  50. }
  51. var time = 0;
  52. function tick(event) {
  53. time = event.time - time > 400 ? event.time : time;
  54. // time based
  55. if(event.time == time){
  56. var head = snake.body[0];
  57. snake.update();
  58. head.x = (head.x <= stage.canvas.width && head.x >= 0) ?
  59. head.x + head.direction.x * cellSize :
  60. head.x < 0 ? stage.canvas.width : 0;
  61. head.y = (head.y <= stage.canvas.height && head.y >= 0) ?
  62. head.y + head.direction.y * cellSize :
  63. head.y < 0 ? stage.canvas.height : 0;
  64. stage.update(event);
  65. }
  66. }
  67. </script>
  68. </head>
  69. <body onload="init();">
  70. <select onchange="createjs.Ticker.setFPS(Number(this.value));">
  71. <option value="10">10 fps</option>
  72. <option value="20" selected>20 fps</option>
  73. <option value="30">30 fps</option>
  74. <option value="40">40 fps</option>
  75. <option value="50">50 fps</option>
  76. <option value="60">60 fps</option>
  77. </select><br>
  78. <canvas id="demoCanvas" width="800" height="700">
  79. alternate content
  80. </canvas>
  81. </body>
  82. </html>