background.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import Sprite from '../base/sprite'
  2. const screenWidth = window.innerWidth
  3. const screenHeight = window.innerHeight
  4. const BG_IMG_SRC = 'images/bg.jpg'
  5. const BG_WIDTH = 512
  6. const BG_HEIGHT = 512
  7. /**
  8. * 游戏背景类
  9. * 提供update和render函数实现无限滚动的背景功能
  10. */
  11. export default class BackGround extends Sprite {
  12. constructor(ctx) {
  13. super(BG_IMG_SRC, BG_WIDTH, BG_HEIGHT)
  14. this.top = 0
  15. this.render(ctx)
  16. }
  17. update() {
  18. this.top += 2
  19. if (this.top >= screenHeight) this.top = 0
  20. }
  21. /**
  22. * 背景图重绘函数
  23. * 绘制两张图片,两张图片大小和屏幕一致
  24. * 第一张漏出高度为top部分,其余的隐藏在屏幕上面
  25. * 第二张补全除了top高度之外的部分,其余的隐藏在屏幕下面
  26. */
  27. render(ctx) {
  28. ctx.drawImage(
  29. this.img,
  30. 0,
  31. 0,
  32. this.width,
  33. this.height,
  34. 0,
  35. -screenHeight + this.top,
  36. screenWidth,
  37. screenHeight
  38. )
  39. ctx.drawImage(
  40. this.img,
  41. 0,
  42. 0,
  43. this.width,
  44. this.height,
  45. 0,
  46. this.top,
  47. screenWidth,
  48. screenHeight
  49. )
  50. }
  51. }