123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- /**
- * 单路画面适应盒
- * @param {HTMLElement} el 视图元素
- * @param {object} options 选项
- * - width 显示宽度
- * - height 显示高度
- * - sourceWidth 源宽度
- * - sourceHeight 源高度
- */
- class SingleChannelFitBox {
- constructor(el, options) {
- this.el = el;
- this.options = options;
- }
- /**
- * 处理宽高适应
- * @param {number} containerWidth 容器宽度
- * @param {number} containerHeight 容器高度
- * @param {bool} inMerge 是否在合图中
- */
- process(containerWidth, containerHeight, inMergeFrame = false) {
- const { width, height, sourceWidth, sourceHeight } = this.options;
- const WHR = width / height;
- const containerWHR = containerWidth / containerHeight;
- let w = containerWidth, h = containerHeight; // 预设视图宽高比与容器相等
- let scale = 1; // 视图->容器 缩放比
- if (WHR < containerWHR) {
- // 适配高度
- scale = containerHeight / height;
- w = width * scale;
- } else {
- // 适配宽度
- scale = containerWidth / width;
- h = height * scale;
- }
- // 是否需要裁剪
- let needCrop = false;
- if (width !== sourceWidth || height !== sourceHeight) {
- const sourceWHR = sourceWidth / sourceHeight;
- if (sourceWHR === WHR) {
- needCrop = inMergeFrame;
- } else {
- needCrop = true;
- }
- }
- // let needCrop = width !== sourceWidth || height != sourceHeight;
- let sw = w, sh = h; // canvas需要设置的尺寸
- if (needCrop) {
- // 分图画面通过css clip自裁剪
- sw = sourceWidth * scale;
- sh = sourceHeight * scale;
- if (inMergeFrame === false) {
- this._resizeSource(sw, sh);
- }
- }
- // 向下取整,避免出现多余的像素
- w = Math.floor(w);
- h = Math.floor(h);
- this._resizeView(w, h);
- return {
- needCrop: needCrop,
- scale: scale,
- canvasWidth: sw,
- canvasHeight: sh,
- };
- }
- _resizeSource(width, height) {
- const $c = $(this.el).find('canvas');
- $c.width(width);
- $c.height(height);
- }
- _resizeView(width, height) {
- const $el = $(this.el);
- $el.width(width);
- $el.height(height);
- }
- }
|