ScaledCanvas.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. setImageSmoothing(flag) {
  19. this.context.imageSmoothingEnabled = flag
  20. }
  21. getPixelRatio() {
  22. let dpr = window.devicePixelRatio || 1;
  23. let bsr = this.context.webkitBackingStorePixelRatio ||
  24. this.context.mozBackingStorePixelRatio ||
  25. this.context.msBackingStorePixelRatio ||
  26. this.context.oBackingStorePixelRatio ||
  27. this.context.backingStorePixelRatio || 1;
  28. return dpr / bsr;
  29. }
  30. onResize = () => {
  31. let ratio = this.getPixelRatio();
  32. let canvasBounds = this.canvas.getBoundingClientRect();
  33. this.canvas.width = canvasBounds.width * ratio;
  34. this.canvas.height = canvasBounds.height * ratio;
  35. this.context.scale(ratio, ratio);
  36. }
  37. getContext() {
  38. return this.context;
  39. }
  40. get pixelWidth() {
  41. return this.canvas.width;
  42. }
  43. get pixelHeight() {
  44. return this.canvas.height;
  45. }
  46. get center() {
  47. return this.bounds.center;
  48. }
  49. get bounds() {
  50. return new Rectangle(0,0, this.canvas.width / this.getPixelRatio(), this.canvas.height / this.getPixelRatio());
  51. }
  52. }