ScaledCanvas.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { Global } from "./Global.js";
  2. import { Rectangle } from "./spatial/Rectangle.js";
  3. export class ScaledCanvas {
  4. constructor(container) {
  5. this.canvas = null;
  6. this.context = null;
  7. this.container = container;
  8. }
  9. clearFrame() {
  10. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  11. }
  12. init() {
  13. this.canvas = document.createElement("canvas");
  14. this.container.appendChild(this.canvas);
  15. this.context = this.canvas.getContext('2d');
  16. window.addEventListener("resize", this.onResize);
  17. this.onResize();
  18. }
  19. getPixelRatio() {
  20. let dpr = window.devicePixelRatio || 1;
  21. let bsr = this.context.webkitBackingStorePixelRatio ||
  22. this.context.mozBackingStorePixelRatio ||
  23. this.context.msBackingStorePixelRatio ||
  24. this.context.oBackingStorePixelRatio ||
  25. this.context.backingStorePixelRatio || 1;
  26. return dpr / bsr;
  27. }
  28. onResize = () => {
  29. let ratio = this.getPixelRatio();
  30. let canvasBounds = this.canvas.getBoundingClientRect();
  31. this.canvas.width = canvasBounds.width * ratio;
  32. this.canvas.height = canvasBounds.height * ratio;
  33. this.context.scale(ratio, ratio);
  34. Global.screenBounds = this.bounds;
  35. }
  36. getContext() {
  37. return this.context;
  38. }
  39. get pixelWidth() {
  40. return this.canvas.width;
  41. }
  42. get pixelHeight() {
  43. return this.canvas.height;
  44. }
  45. get center() {
  46. return this.bounds.center;
  47. }
  48. get bounds() {
  49. return new Rectangle(0,0, this.canvas.width / this.getPixelRatio(), this.canvas.height / this.getPixelRatio());
  50. }
  51. }