single_fitbox.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * 单路画面适应盒
  3. * @param {HTMLElement} el 视图元素
  4. * @param {object} options 选项
  5. * - width 显示宽度
  6. * - height 显示高度
  7. * - sourceWidth 源宽度
  8. * - sourceHeight 源高度
  9. */
  10. class SingleChannelFitBox {
  11. constructor(el, options) {
  12. this.el = el;
  13. this.options = options;
  14. }
  15. /**
  16. * 处理宽高适应
  17. * @param {number} containerWidth 容器宽度
  18. * @param {number} containerHeight 容器高度
  19. * @param {bool} inMerge 是否在合图中
  20. */
  21. process(containerWidth, containerHeight, inMergeFrame = false) {
  22. const { width, height, sourceWidth, sourceHeight } = this.options;
  23. const WHR = width / height;
  24. const containerWHR = containerWidth / containerHeight;
  25. let w = containerWidth, h = containerHeight; // 预设视图宽高比与容器相等
  26. let scale = 1; // 视图->容器 缩放比
  27. if (WHR < containerWHR) {
  28. // 适配高度
  29. scale = containerHeight / height;
  30. w = width * scale;
  31. } else {
  32. // 适配宽度
  33. scale = containerWidth / width;
  34. h = height * scale;
  35. }
  36. // 是否需要裁剪
  37. let needCrop = false;
  38. if (width !== sourceWidth || height !== sourceHeight) {
  39. const sourceWHR = sourceWidth / sourceHeight;
  40. if (sourceWHR === WHR) {
  41. needCrop = inMergeFrame;
  42. } else {
  43. needCrop = true;
  44. }
  45. }
  46. // let needCrop = width !== sourceWidth || height != sourceHeight;
  47. let sw = w, sh = h; // canvas需要设置的尺寸
  48. if (needCrop) {
  49. // 分图画面通过css clip自裁剪
  50. sw = sourceWidth * scale;
  51. sh = sourceHeight * scale;
  52. if (inMergeFrame === false) {
  53. this._resizeSource(sw, sh);
  54. }
  55. }
  56. // 向下取整,避免出现多余的像素
  57. w = Math.floor(w);
  58. h = Math.floor(h);
  59. this._resizeView(w, h);
  60. return {
  61. needCrop: needCrop,
  62. scale: scale,
  63. canvasWidth: sw,
  64. canvasHeight: sh,
  65. };
  66. }
  67. _resizeSource(width, height) {
  68. const $c = $(this.el).find('canvas');
  69. $c.width(width);
  70. $c.height(height);
  71. }
  72. _resizeView(width, height) {
  73. const $el = $(this.el);
  74. $el.width(width);
  75. $el.height(height);
  76. }
  77. }