/**
|
* 转换尺寸 canvas缩放后 返回的尺寸不对 要做调整
|
* @param {[type]} width canvas的CSS宽度
|
* @param {[type]} height canvas的CSS高度
|
* @param {[type]} canvasWidth canvas的画布宽度
|
* @param {[type]} canvasHeight canvas的画布高度
|
* @param {[type]} obj 需要转换的尺寸对象
|
* @return {[type]} 转换后的尺寸对象
|
*/
|
const transSize = function (width, height, canvasWidth, canvasHeight, obj) {
|
if (!obj) {
|
return {
|
width: 0,
|
height: 0,
|
left: 0,
|
top: 0,
|
right: 0,
|
bottom: 0
|
};
|
}
|
const res = {};
|
let _ratio;
|
const ratio = canvasWidth / canvasHeight;
|
// 如果宽高比大于画布的宽高比 则比例以高度来计算 反之以宽度计算
|
if (width / height > ratio) {
|
_ratio = height / canvasHeight;
|
const _width = (width - height * ratio) / 2;
|
res.width = typeof obj.width === 'number' ? obj.width * _ratio : obj.width;
|
res.height = typeof obj.height === 'number' ? obj.height * _ratio : obj.height;
|
res.top = obj.top * _ratio;
|
res.bottom = obj.bottom * _ratio;
|
res.left = obj.left * _ratio + _width;
|
res.right = obj.right * _ratio + _width;
|
} else {
|
_ratio = width / canvasWidth;
|
const _height = (height - width / ratio) / 2;
|
res.width = typeof obj.width === 'number' ? obj.width * _ratio : obj.width;
|
res.height = typeof obj.height === 'number' ? obj.height * _ratio : obj.height;
|
res.top = obj.top * _ratio + _height;
|
res.bottom = obj.bottom * _ratio + _height;
|
res.left = obj.left * _ratio;
|
res.right = obj.right * _ratio;
|
}
|
// console.log('trans', res, 'obj', obj);
|
// console.trace('transSize callStack');
|
return res;
|
};
|
|
// 防抖
|
const debounce = function (fn, delay = 500) {
|
var timer = null;
|
return function () {
|
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
var _this = this;
|
var args = arguments;
|
if (timer) clearTimeout(timer);
|
timer = setTimeout(function () {
|
fn.apply(_this, args);
|
}, delay);
|
};
|
};
|
|
// 节流
|
const throttle = function (fn, delay = 300) {
|
var lastTime, timer;
|
return function () {
|
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
var _this = this;
|
var args = arguments;
|
var nowTime = Date.now();
|
if (lastTime && nowTime - lastTime < delay) {
|
if (timer) clearTimeout(timer);
|
timer = setTimeout(function () {
|
lastTime = nowTime;
|
fn.apply(_this, args);
|
}, delay);
|
} else {
|
lastTime = nowTime;
|
fn.apply(_this, args);
|
}
|
};
|
};
|
|
/**
|
* 执行指定次数的定时器
|
* @param {回调} func
|
* @param {等待时间} w
|
* @param {重复次数} t
|
*/
|
const interval = function (func, w, t) {
|
const interv = function () {
|
if (typeof t === 'undefined' || t-- > 0) {
|
setTimeout(interv, w);
|
try {
|
// eslint-disable-next-line no-useless-call
|
func.call(null);
|
} catch (e) {
|
t = 0;
|
throw e.toString();
|
}
|
}
|
};
|
|
setTimeout(interv, w);
|
};
|
|
export default {
|
debounce,
|
interval,
|
throttle,
|
transSize
|
};
|