boxgame.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. function BoxGame() {
  2. var container = null;
  3. var canvas = null;
  4. var contextType = '2d';
  5. var contextAttributes = {};
  6. var context = null;
  7. var game = null;
  8. var boxes = [];
  9. this.create = function(elementName) {
  10. game = this;
  11. container = document.getElementById(elementName);
  12. canvas = container.getElementsByTagName('canvas')[0];
  13. window.addEventListener('resize', game.handleResize);
  14. canvas.addEventListener('mousemove', game.handleMouseMove);
  15. window.requestAnimationFrame(game.handleRequestAnimationFrame);
  16. this.handleResize(null);
  17. };
  18. this.handleResize = function(event) {
  19. canvas.width = container.offsetWidth;
  20. canvas.height = container.offsetHeight;
  21. context = canvas.getContext(contextType, contextAttributes);
  22. context.translate(0.5, 0.5);
  23. game.init(canvas);
  24. }
  25. this.handleRequestAnimationFrame = function(event) {
  26. game.update(canvas);
  27. context.fillStyle = "#FFFFFF";
  28. context.fillRect(0 ,0, canvas.width, canvas.height);
  29. game.draw(context);
  30. window.requestAnimationFrame(game.handleRequestAnimationFrame);
  31. }
  32. this.handleMouseMove = function(event) {
  33. game.mouseMove(canvas, event.offsetX, event.offsetY);
  34. }
  35. this.init = function(canvas) {
  36. boxes = [];
  37. var boxDensity = Math.floor((canvas.width * canvas.height) / 2000);
  38. for(var i = 0; i < boxDensity; i++) {
  39. boxes.push(new Box());
  40. }
  41. /*for(var i = 0; i < 100; i++) {
  42. boxes.push(new Circle());
  43. }*/
  44. /*for(var i = 0; i < boxDensity; i++) {
  45. boxes.push(new BinaryFloater());
  46. }*/
  47. /*for(var i = 0; i < 25; i++) {
  48. boxes.push(new Triangle());
  49. }*/
  50. /*for(var i = 0; i < 25; i++) {
  51. boxes.push(new StarShape());
  52. }*/
  53. for(var i = 0, box = boxes[0]; box = boxes[i]; i++) {
  54. box.init(canvas);
  55. }
  56. };
  57. this.update = function(canvas) {
  58. for(var i = 0, box = boxes[0]; box = boxes[i]; i++) {
  59. box.update(canvas);
  60. }
  61. };
  62. this.draw = function(context) {
  63. for(var i = 0, box = boxes[0]; box = boxes[i]; i++) {
  64. box.draw(context);
  65. }
  66. };
  67. this.mouseMove = function(canvas, x, y) {
  68. };
  69. }