scenery.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. function Scenery(camera, parallax) {
  2. this.position = {x: 0, y: 0};
  3. this.width = 786;
  4. this.height = 786;
  5. this.spriteCanvas = null;
  6. this.spriteContext = null;
  7. this.canvasWidth = 128;
  8. this.canvasHeight = 128;
  9. this.debug = false;
  10. this.parallaxDepth = parallax;
  11. this.update = function(canvas) {
  12. this.canvasWidth = canvas.width;
  13. this.canvasHeight = canvas.height;
  14. var truePos = {x: 0, y: 0};
  15. truePos.x = (camera.x * this.parallaxDepth) + this.position.x;
  16. truePos.y = (camera.y * this.parallaxDepth) + this.position.y;
  17. if(truePos.x < -this.width) {
  18. this.position.x += this.width;
  19. }
  20. if(truePos.x > 0) {
  21. this.position.x -= this.width;
  22. }
  23. if(truePos.y < -this.height) {
  24. this.position.y += this.height;
  25. }
  26. if(truePos.y > 0) {
  27. this.position.y -= this.height;
  28. }
  29. }
  30. this.preRender = function() {
  31. if(this.spriteContext == null) {
  32. this.spriteCanvas = document.createElement("canvas");
  33. this.spriteCanvas.width = this.width;
  34. this.spriteCanvas.height = this.height;
  35. this.spriteContext = this.spriteCanvas.getContext("2d");
  36. this.spriteContext.fillStyle = "#DDDDDD";
  37. var starCount = parseInt(Math.sqrt(this.width));
  38. for(var i = 0; i < starCount; i++) {
  39. var position = {x: parseInt(this.width * Math.random()), y: parseInt(this.height * Math.random())};
  40. this.spriteContext.beginPath();
  41. this.spriteContext.arc(position.x, position.y, parseInt((20 * this.parallaxDepth) * Math.random() + 1), 0, 2 * Math.PI);
  42. this.spriteContext.fill();
  43. }
  44. }
  45. }
  46. this.draw = function(context) {
  47. this.preRender();
  48. var truePos = {x: 0, y: 0};
  49. truePos.x = (camera.x * this.parallaxDepth) + this.position.x;
  50. truePos.y = (camera.y * this.parallaxDepth) + this.position.y;
  51. for(var x = 0; x < this.canvasWidth / this.width + 1; x++) {
  52. for(var y = 0; y < this.canvasHeight / this.height + 1; y++) {
  53. context.drawImage(this.spriteCanvas, truePos.x + (x * this.width), truePos.y + (y * this.height));
  54. }
  55. }
  56. if(this.debug) {
  57. context.strokeStyle = "#33DD33";
  58. context.lineWidth = 3;
  59. context.beginPath();
  60. context.rect(truePos.x, truePos.y, this.width, this.height);
  61. context.stroke();
  62. }
  63. }
  64. };