background.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. function Background(camera) {
  2. this.position = {x: 0, y: 0};
  3. this.width = 128;
  4. this.height = 128;
  5. this.spriteCanvas = null;
  6. this.spriteContext = null;
  7. this.canvasWidth = 128;
  8. this.canvasHeight = 128;
  9. this.init = function() {
  10. this.preRender();
  11. }
  12. this.update = function(canvas) {
  13. this.canvasWidth = canvas.width;
  14. this.canvasHeight = canvas.height;
  15. var truePos = {x: 0, y: 0};
  16. truePos.x = camera.position.x + this.position.x;
  17. truePos.y = camera.position.y + this.position.y;
  18. if(truePos.x < -this.width) {
  19. this.position.x += this.width;
  20. }
  21. if(truePos.x > 0) {
  22. this.position.x -= this.width;
  23. }
  24. if(truePos.y < -this.height) {
  25. this.position.y += this.height;
  26. }
  27. if(truePos.y > 0) {
  28. this.position.y -= this.height;
  29. }
  30. }
  31. this.preRender = function() {
  32. if(this.spriteContext == null) {
  33. this.spriteCanvas = document.createElement("canvas");
  34. this.spriteCanvas.width = this.width + 1;
  35. this.spriteCanvas.height = this.height + 1;
  36. this.spriteContext = this.spriteCanvas.getContext("2d");
  37. this.spriteContext.beginPath();
  38. this.spriteContext.rect(0, 0, this.width, this.height);
  39. this.spriteContext.fillStyle = "lightgray";
  40. this.spriteContext.fill();
  41. }
  42. }
  43. this.draw = function(context) {
  44. for(var x = 0; x < this.canvasWidth / this.width + 1; x++) {
  45. for(var y = 0; y < this.canvasHeight / this.height + 1; y++) {
  46. context.drawImage(this.spriteCanvas, this.position.x + (x * this.width), this.position.y + (y * this.height));
  47. }
  48. }
  49. }
  50. };