ScaledCanvas.js 1.6 KB

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