UNPKG

vue_h5_tools

Version:
277 lines (272 loc) 8.83 kB
import moment from 'moment' import EXIF from 'exif-js' // import Vue from 'vue' const canvas = document.createElement('canvas') const ctx = canvas.getContext('2d') ctx.fillStyle = 'rgba(255,255,255,0)' export default { canvas, ctx, isWeixin: function() { var ua = navigator.userAgent.toLowerCase() return String(ua.match(/MicroMessenger/i)) === 'micromessenger' }, getLocalTimeString: function() { return moment().format('YYYY-MM-DD HH:mm:ss') }, // 随机数 randomNum: function(val, less_val = true) { return less_val ? Math.floor(Math.random() * val) : Math.ceil(Math.random() * val) }, isIphone: function() { const ua = navigator.userAgent.toLowerCase() return String(ua.match(/iphone/i)) === 'iphone' }, // 通过正则匹配获取当前页面的url中的参数 getUrlParam: function(name) { const _url = location.href const reg = new RegExp('(^.*)(' + name + '=)([^&]*)(&?)(.*$)') const res = _url.match(reg) const val = res ? unescape(res[3]) : '' // console.log(_url, res,val) return val }, // 删除路径中的api参数 removeHashParamApi: function(_path) { // 去掉api_token字段 const reg = new RegExp('(^.*)(api_token=.*)$') const val = _path.match(reg); let path path = val ? val[1] : _path // 去掉最后的?、&、?&号 path = path.replace(/(&)$/g, '') path = path.replace(/(\?)$/g, '') path = path.replace(/(\?&)$/g, '') return path }, // 删除路径中的api参数 checkApiToken: function(to) { let path, api_token const _url = decodeURIComponent(to.path) const reg = new RegExp('(^.*)(&\\|&)(api_token)(.*)(api_token)(&\\|&)(.*)') const val = _url.match(reg) if (val) { path = val[1] api_token = val[4] } // console.log(to.path, val, path, api_token) return { path, api_token } }, // 预读图片 preLoadImage: function(data, debug) { return new Promise((resolve, reject) => { if (debug) { console.log(data) } const image = new Image() image.onload = () => { this.sleep(10).then(() => { resolve(image) }) } // image.crossOrigin = 'anonymous'; image.src = data if (data.indexOf('data:') === 0 && data.split(',')[1] === '') { reject('图片数据为空') } }) }, // 图片按比例缩放 imageScale: function(image, scaleX = 1, scaleY = 1, quality = 1) { scaleY = scaleY || scaleX canvas.width = image.width * scaleX canvas.height = image.height * scaleY // console.log(scaleX,scaleY,canvas.width,canvas.height,image.width,image.height) return new Promise((resolve, reject) => { ctx.scale(scaleX, scaleY) ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.drawImage(image, 0, 0) resolve(canvas.toDataURL('image/jpeg', quality)) }) }, // 图片按指定宽度高度缩放 async imageScaleTo(data, toWidth, toHeight = null, quality = 1) { const image = await this.preLoadImage(data) var scaleX, scaleY if (!toHeight) { toHeight = toWidth * (image.height / image.width) } if (!toWidth) { toWidth = toHeight * (image.width / image.height) } scaleX = toWidth / image.width scaleY = toHeight / image.height return this.imageScale(image, scaleX, scaleY, quality) }, // 图片按指定面积缩小,不超过不缩小 async imageScaleToArea(data, toWidth = null, toHeight = null, quality = 1) { const image = await this.preLoadImage(data) var ratio, toArea, scaleX, scaleY // 没设定长度,就取回图片的原宽度与高度 toWidth = toHeight || image.width toHeight = toHeight || image.height // 图片缩小后的面积 toArea = toWidth * toHeight // 图片的宽高比 ratio = image.width / image.height if (image.width > toWidth && image.height > toHeight) { // 宽度、高度都超过指定值的情况 if (toWidth * (toWidth / ratio) <= toArea) { scaleX = scaleY = toWidth / image.width } else { scaleX = scaleY = toHeight / image.height } } else if (image.width > toWidth) { // 只有宽度超过指定值的情况 scaleX = scaleY = toWidth / image.width } else if (image.height > toHeight) { // 只有高度超过指定值的情况 scaleX = scaleY = toHeight / image.height } // console.log(scaleX,scaleY,toWidth,toHeight,image.width,image.height) return this.imageScale(image, scaleX, scaleY, quality) }, // 图片根据陀螺仪自动旋转 imageRotation: function(data, orientation, quality = 1) { return new Promise(async(resolve, reject) => { const image = await this.preLoadImage(data) let toR = 0 let toX = 0 let toY = 0 switch (orientation) { case 1: canvas.width = image.width canvas.height = image.height break case 3: canvas.width = image.width canvas.height = image.height toR = 180 toX = -image.width toY = -image.height break case 6: canvas.width = image.height canvas.height = image.width toR = 90 toY = -image.height break case 8: canvas.width = image.height canvas.height = image.width toR = -90 toX = -image.width break default: canvas.width = image.width canvas.height = image.height } ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.rotate(toR * Math.PI / 180) ctx.translate(toX, toY) ctx.drawImage(image, 0, 0) resolve(canvas.toDataURL('image/jpeg', quality)) }) }, // 获取照片的陀螺仪旋转方向 getEXIF: function(data, TagName = null) { return new Promise(async(resolve, reject) => { const image = await this.preLoadImage(data) EXIF.getData(image, function() { // var orientation = EXIF.getTag(this, 'Orientation') if (TagName) { resolve(EXIF.getTag(this, TagName)) } else { resolve(EXIF.getAllTags(this)) } }) }) }, /** * 将以base64的图片url数据转换为Blob * @param urlData * 用url方式表示的base64图片数据 */ convertBase64UrlToBlob: function(urlData) { var bytes = window.atob(urlData.split(',')[1]) // 去掉url的头,并转换为byte // 处理异常,将ascii码小于0的转换为大于0 var ab = new ArrayBuffer(bytes.length) var ia = new Uint8Array(ab) for (var i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i) } return new Blob([ab], { type: 'image/png' }) }, sleep: (Millisecond) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve() }, Millisecond) }) }, // 删除左右两端的空格 trim: function(str) { return str.replace(/(^\s*)|(\s*$)/g, '') }, // 删除左边的空格 ltrim: function(str, older, newer = '') { return str.replace(new RegExp(`^[${older}]+`, 'g'), newer) }, // 删除右边的空格 rtrim: function(str, older, newer = '') { return str.replace(new RegExp(`[${older}]+$`, 'g'), newer) }, getDomParents(el, classname, parentSelector) { let exist = false if (parentSelector === undefined) { parentSelector = document } const parents = [] let p = el.parentNode if (el.classList.value.indexOf(classname) > -1) { return true } while (p !== parentSelector) { if (p.classList.value.indexOf(classname) > -1) { exist = true break } const o = p parents.push(o) p = o.parentNode } parents.push(parentSelector) // Push that parentSelector you wanted to stop at return exist }, preventDefault(classname = 'can_scroll') { // 阻止页面回弹 const _this = this document.body.addEventListener('touchmove', function(e) { if (!_this.getDomParents(e.target, classname)) { // 阻止默认的处理方式(阻止下拉滑动的效果) e.preventDefault() } }, { passive: false }) // passive 参数不能省略,用来兼容ios和android }, // 获取canvas图片数据,转成blob jpg文件 async getCanvasBlob(_canvas = null, _imageData = null) { _canvas = _canvas || canvas if (_imageData) { const image = await this.preLoadImage(_imageData) _canvas.width = image.width _canvas.height = image.height const _ctx = canvas.getContext('2d') _ctx.drawImage(image, 0, 0, _canvas.width, _canvas.height) } return new Promise(async(resolve, reject) => { _canvas.toBlob((blob) => { resolve(blob) }, 'image/jpeg') }) } }