renderer_2d.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. export class Canvas2DRenderer {
  2. canvas = null;
  3. ctx = null;
  4. getShowData = null;
  5. storage = [];
  6. constructor(canvas, getShowData, outputLayer) {
  7. this.canvas = canvas;
  8. this.ctx = canvas.getContext('2d');
  9. this.getShowData = getShowData;
  10. this.outputLayer = outputLayer;
  11. }
  12. #ArraysAreEqual(arr1, arr2) {
  13. if (arr1.length !== arr2.length) {
  14. return false;
  15. }
  16. return arr1.every(function (val, index) {
  17. return val === arr2[index];
  18. });
  19. }
  20. #DrawBox(arr) {
  21. if (arr.length) {
  22. for (let i = 0; i < arr.length; i++) {
  23. this.ctx.strokeStyle = 'red';
  24. this.ctx.lineWidth = 10;
  25. if (this.outputLayer) {
  26. let [x, y, w, h] = [
  27. arr[i].x * this.outputLayer.WidthRatio,
  28. arr[i].y * this.outputLayer.HeightRatio,
  29. arr[i].w * this.outputLayer.WidthRatio,
  30. arr[i].h * this.outputLayer.HeightRatio,
  31. ];
  32. this.ctx.strokeRect(x, y, w, h);
  33. this.storage = [x, y, w, h];
  34. } else {
  35. this.ctx.strokeRect(arr[i].x, arr[i].y, arr[i].w, arr[i].h);
  36. this.storage = [arr[i].x, arr[i].y, arr[i].w, arr[i].h];
  37. }
  38. }
  39. } else {
  40. let [x, y, w, h] = this.storage;
  41. this.ctx.strokeStyle = 'transparent';
  42. this.ctx.lineWidth = 10;
  43. this.ctx.strokeRect(x, y, w, h);
  44. }
  45. }
  46. temp = null;
  47. draw(frame) {
  48. this.canvas.width = frame.displayHeight;
  49. this.canvas.height = frame.displayWidth;
  50. this.ctx.translate(frame.displayHeight, 0);
  51. this.ctx.rotate(Math.PI / 2);
  52. this.ctx.drawImage(frame, 0, 0, frame.displayWidth, frame.displayHeight);
  53. if (self.GetImg) {
  54. this.ctx.canvas.convertToBlob().then((blob) => {
  55. self.postMessage({ img: blob, type: 'img' });
  56. });
  57. self.GetImg = false;
  58. }
  59. const showData = this.getShowData();
  60. if (showData) {
  61. this.#DrawBox(showData);
  62. }
  63. frame.close();
  64. }
  65. }