ScaledCanvas.js 1.9 KB

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