一些(实用)的基础工具函数

198 阅读4分钟

字符宽度计算函数

/**
 *字符宽度计算函数
 fontSize:字号
 fontFamily:字体样式
 text:要计算的字符
 */

function textHandle(fontSize, text, fontFamily = "Arial") {
    var span = document.createElement("span");
    var result = {};
    result.width = span.offsetWidth;
    result.height = span.offsetHeight;
    span.style.visibility = "hidden";
    span.style.fontSize = fontSize;
    span.style.fontFamily = fontFamily;
    span.style.display = "inline-block";
    span.classNmae = "text_Handle";
    document.body.appendChild(span);
    if (typeof span.textContent != "undefined") {
        span.textContent = text;
    } else {
        span.innerText = text;
    }
    result.width = parseFloat(window.getComputedStyle(span).width) - result.width;
    result.height = parseFloat(window.getComputedStyle(span).height) - result.height;
    return result;
}

调用示例:
textHandle("14px""abc3.1415#fff测试一下").width

最后操作完将所有.text_Handle元素删除

文字自动居中和左对齐

.content{
    text-align: center;
}
.text{
    display: inline-block;
    text-align: left;
}
<div class="content">
    <span class="text">这段文字能不能这样判断一下,当文字不足一行时,让它居中显示,当文字超过一行就让它居左</span>
</div>

在线视频画面-自定义位置截取

/**
    url(为.MP4的视频链接)
    frame(要截取的位置,我这里默认为5)
*/
function videoScreenImg(url, frame = 5) {
    let video = document.createElement("VIDEO");
    // 截图缩放比例
    let slide = 0.5;
    // 可能会出现跨域现象,这里设置
    video.crossOrigin = "anonymous";
    video.setAttribute("src", url);
    // 自定义截取的位置(可以不设置,因为有个默认值,但是最好是不要为0)
    video.currentTime = frame
    // 使用promise因为canvas绘图需要时间,这里采用异步返回
    return new Promise((resolve, reject) => {
        // 这里是video的监听函数,监听video就绪之后就开始使用canvas绘图
        video.addEventListener('loadeddata', function () {
            let canvas = document.createElement("canvas");
            canvas.width = video.videoWidth * slide;
            canvas.height = video.videoHeight * slide;
            // 获取画板上下文执行绘图,直接把video放进去就可以了
            canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
            resolve(canvas.toDataURL("image/png"))
        });
    })
}

// 测试链接
let myurl = 'http://vali.cp31.ott.cibntv.net/6977BAFBDAD3D71A18D4052FB/03000A02015D32052DCA865155028267B1FE01-D8B0-4610-86E8-CA49C25ED295.mp4?ccode=0512&duration=219&expire=18000&psid=36545cfed468138047162ff58632e78943346&ups_client_netip=b70e1da9&ups_ts=1641880331&ups_userid=&utid=G1CRGQOBwBoCAbcOH9EjUvi6&vid=XMTY0OTk4MzM2MA&vkey=B95bcf587848bd457dee8534e58d49490&eo=1&t=f4cff03c9bb0eaa&cug=1&rid=20000000D23937D838D7C68BC5D5778AD09681B302000000&type=mp4sd&bc=2&dre=u20&si=44&dst=1'

videoScreenImg(myurl).then(res => {
    // 这里就可以获取到你想要的视频帧图片
    // 如果报跨域或者403,请自己去找一个不会跨域,不会403的视频链接
    // 或者你也可以自己搞一个本地的视频,然后起一个服务,用本地地址来测试
    console.log(res)
})

判断图片资源是否有效

// 判断图片资源是否有效
function imgUrlIsError(imgurl) {
    return new Promise(function (resolve, reject) {
        var ImgObj = new Image();
        ImgObj.src = imgurl;
        ImgObj.onload = function (res) {
            resolve(res);
            console.log('成功:', res);
            return 1
        }
        ImgObj.onerror = function (err) {
            reject(err)
            console.log('失败:', err);
            return -1
        }
    }).catch((e) => { });
}

测试示例:
imgUrlIsError('https://cdn9-banquan.ituchong.com/weili/l/914495302984269898.webp') // 成功
imgUrlIsError('https://cdn9-banquan.ituchong.com/weili/l/914495302984269898_NO.webp') // 失败

对象深冻结

// 深冻结函数.
function deepFreeze(obj) {
    // 取回定义在obj上的属性名
    var propNames = Object.getOwnPropertyNames(obj);
    // 在冻结自身之前冻结属性
    propNames.forEach(function (name) {
        var prop = obj[name];
        // 如果prop是个对象,冻结它
        if (typeof prop == 'object' && prop !== null)
            deepFreeze(prop);
    });
    // 冻结自身
    return Object.freeze(obj);
}

base64转换为file格式

function dataURLtoFile(base64, filename) {//将base64转换为文件,参数filename请记得自己加后缀
    var arr = base64.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}

调用示例:
var base64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACUAAAAVCAIAAABOhrD5AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAEXRFWHRTb2Z0d2FyZQBTbmlwYXN0ZV0Xzt0AAAAmSURBVEiJY9TT02OgI2Cip2Wj9o3aN2rfqH2j9o3aN2rfqH1UAAC9NwC0F384xAAAAABJRU5ErkJggg=='
var res = dataURLtoFile(base64, 'testDemo.png')
console.log(res);

image.png

格林威治时间转换

function GMTToStr(time) {
    var now = new Date(time)
    var year = now.getFullYear()
    var mon = now.getMonth() + 1
    var date = now.getDate()
    var hours = now.getHours()
    var minutes = now.getMinutes()
    var sec = now.getSeconds()
    if (mon < 10) { mon = '0' + mon }
    if (date < 10) { date = '0' + date }
    if (minutes < 10) { minutes = '0' + minutes }
    if (hours < 10) { hours = '0' + hours }
    if (sec < 10) { sec = '0' + sec }
    var postDate =
        year + '-' + mon + '-' + date + ' ' + hours + ':' + minutes + ':' + sec
    return postDate
}

// 调用示例
var res = GMTToStr('Thu Jun 22 2021 19:07:30 GMT+0800')
console.log(res) // 2021-06-22 19:07:30

时间戳转换

function timesTamp(mytime) {
    // 注意:这里的 mytime 是毫秒级别的,如果原始数据是秒级别的,
    // 请传参时将 mytime 乘以1000再传进来
    var date = new Date(mytime)
    var YY = date.getFullYear() + '-'
    var MM =
        (date.getMonth() + 1 < 10
            ? '0' + (date.getMonth() + 1)
            : date.getMonth() + 1) + '-'
    var DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    var hh =
        (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
    var mm = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes() + ':'
    var ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    var newtime = YY + MM + DD + ' ' + hh + mm + ss
    return newtime
}

var res = timesTamp(1641882063196)
console.log(res) // 2022-01-11 14:21:03

数组去重,有点类似bitmap

这里利用的是对象内的key值是唯一的特性进行处理的

function arrayDuplicate(array) {
    const obj = {}
    var l = -1
    while (l < array.length - 1) { obj[array[l += 1]] = 1 }
    return Object.keys(obj)
}

// 调用示例
var array = [1, 1, 1, 1, 12, 2, 2, 3, 3, 3, 4, 4,]
console.log(arrayDuplicate(array))


// 根据上面的例子,可以举一反三,还可以这样,这里我就不封装了
var array = [
    { id: 123, name: 'xiaoming' },
    { id: 123, name: 'xiaoming' },
    { id: 123, name: 'xiaoming' },
    { id: 123, name: 'xiaoming' },
    { id: 456, name: 'xiahua' },
    { id: 456, name: 'xiahua' },
    { id: 789, name: 'hahaha' },
    { id: 789, name: 'hahaha' },
    { id: 789, name: 'hahaha' }
]

var tempobj = {}
for (let i = 0; i < array.length; i++) {
    var item = array[i];
    tempobj[item.name] = item
}

console.log(Object.values(tempobj))

大佬们,以上内容有不对的地方欢迎指出