starfield.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. function Starfield() {
  2. var stars = [];
  3. var offset = { x: 0, y: 0 };
  4. var targetOffset = { x: 0, y: 0 };
  5. var velocity = { x: -1, y: -1 };
  6. var size = { width: 300, height: 300 };
  7. var debug = false;
  8. var depth = 0;
  9. this.init = function (canvas, fieldDepth, fieldVelocity) {
  10. size.width = canvas.width;
  11. size.height = canvas.height;
  12. depth = fieldDepth;
  13. offset.x = (size.width / 2) / depth;
  14. offset.y = (size.height / 2) / depth;
  15. targetOffset.x = (size.width / 2) / depth;
  16. targetOffset.y = (size.height / 2) / depth;
  17. velocity.x = fieldVelocity.x;
  18. velocity.y = fieldVelocity.y;
  19. var starDensity = Math.floor((size.width * size.height) / 10000);
  20. for (var i = 0; i < starDensity; i++) {
  21. stars.push(new Star());
  22. }
  23. for (var i = 0, star = stars[0]; star = stars[i]; i++) {
  24. star.init(canvas);
  25. }
  26. };
  27. this.update = function (canvas) {
  28. offset.x += (0.01 / (depth + 1)) * (targetOffset.x - offset.x)
  29. offset.y += (0.01 / (depth + 1)) * (targetOffset.y - offset.y)
  30. if (offset.x > size.width) {
  31. offset.x -= size.width;
  32. targetOffset.x = offset.x;
  33. }
  34. if (offset.y > size.height) {
  35. offset.y -= size.height;
  36. targetOffset.y = offset.y;
  37. }
  38. if (offset.x < 0) {
  39. offset.x += 2 * size.width;
  40. targetOffset.x = offset.x;
  41. }
  42. if (offset.y < 0) {
  43. offset.y += 2 * size.height;
  44. targetOffset.y = offset.y;
  45. }
  46. for (var i = 0, star = stars[0]; star = stars[i]; i++) {
  47. star.update(canvas);
  48. }
  49. };
  50. this.draw = function (context) {
  51. var xoffset = { x: offset.x - size.width, y: offset.y };
  52. var yoffset = { x: offset.x, y: offset.y - size.height };
  53. var fulloffset = { x: xoffset.x, y: yoffset.y };
  54. if (debug) {
  55. context.strokeStyle = "#00FF00";
  56. context.beginPath();
  57. context.rect(offset.x, offset.y, size.width, size.height);
  58. context.rect(xoffset.x, xoffset.y, size.width, size.height);
  59. context.rect(yoffset.x, yoffset.y, size.width, size.height);
  60. context.rect(fulloffset.x, fulloffset.y, size.width, size.height);
  61. context.stroke();
  62. }
  63. context.fillStyle = "#FFFFFF";
  64. for (var i = 0, star = stars[0]; star = stars[i]; i++) {
  65. star.draw(context, offset);
  66. star.draw(context, xoffset);
  67. star.draw(context, yoffset);
  68. star.draw(context, fulloffset);
  69. }
  70. };
  71. this.mouseMove = function (canvas, x, y) {
  72. if (depth != 0) {
  73. targetOffset.x = x / depth;
  74. targetOffset.y = y / depth;
  75. }
  76. };
  77. }