Engine.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. class Engine {
  2. framerate = 60;
  3. canvas = null;
  4. context = null;
  5. viewport = {w:200, h: 160};
  6. constructor(containingElement) {
  7. this.canvas = document.createElement('canvas');
  8. this.canvas.width = this.viewport.w;
  9. this.canvas.height = this.viewport.h;
  10. this.context = this.canvas.getContext('2d');
  11. containingElement.appendChild(this.canvas);
  12. }
  13. attach(drawObject) {
  14. this.drawObject = drawObject;
  15. this.lastTime = new Date().getTime();
  16. window.requestAnimationFrame(this.draw);
  17. }
  18. draw = () => {
  19. let currentTime = new Date().getTime();
  20. let deltams = currentTime - this.lastTime;
  21. let expectedDelta = 1000/this.framerate;
  22. let delta = deltams / expectedDelta;
  23. this.drawObject.update(delta);
  24. this.context.save();
  25. this.context.setTransform(1, 0, 0, 1, 0, 0);
  26. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  27. this.context.restore();
  28. this.context.save();
  29. this.context.translate(0.5, 0.5);
  30. this.drawObject.draw(this.context);
  31. this.context.restore();
  32. this.lastTime = currentTime;
  33. window.requestAnimationFrame(this.draw);
  34. }
  35. }