background.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. function Background(camera) {
  2. this.position = {x: 0, y: 0};
  3. this.width = 768;
  4. this.height = 768;
  5. this.spriteCanvas = null;
  6. this.spriteContext = null;
  7. this.canvasWidth = 768;
  8. this.canvasHeight = 768;
  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.translate(0.5, 0.5);
  38. this.spriteContext.strokeStyle = "gold";
  39. /*var columns = parseInt(Math.sqrt(this.width));
  40. var rows = parseInt(Math.sqrt(this.height));*/
  41. var columns = parseInt(this.width / 128);
  42. var rows = parseInt(this.height / 128);
  43. for(var i = 0; i < columns; i++) {
  44. this.spriteContext.beginPath();
  45. this.spriteContext.moveTo(i * (this.width / columns), 1);
  46. this.spriteContext.lineTo(i * (this.width / columns), this.height);
  47. this.spriteContext.stroke();
  48. }
  49. for(var i = 0; i < rows; i++) {
  50. this.spriteContext.beginPath();
  51. this.spriteContext.moveTo(1, i * (this.height / rows));
  52. this.spriteContext.lineTo(this.width, i * (this.height / rows));
  53. this.spriteContext.stroke();
  54. }
  55. }
  56. }
  57. this.draw = function(context) {
  58. for(var x = 0; x < this.canvasWidth / this.width + 1; x++) {
  59. for(var y = 0; y < this.canvasHeight / this.height + 1; y++) {
  60. context.drawImage(this.spriteCanvas, this.position.x + (x * this.width), this.position.y + (y * this.height));
  61. }
  62. }
  63. }
  64. };