mirror of
https://github.com/wanglin2/mind-map.git
synced 2026-02-21 10:27:44 +08:00
Demo:默认压缩选择的节点图片
This commit is contained in:
parent
d8df80147d
commit
4de35fca9c
@ -29,6 +29,8 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { compressImage } from '@/utils'
|
||||
|
||||
export default {
|
||||
model: {
|
||||
prop: 'value',
|
||||
@ -60,12 +62,12 @@ export default {
|
||||
},
|
||||
|
||||
// 选择图片
|
||||
selectImg(file) {
|
||||
this.file = file
|
||||
let fr = new FileReader()
|
||||
fr.readAsDataURL(file)
|
||||
fr.onload = e => {
|
||||
this.$emit('change', e.target.result)
|
||||
async selectImg(file) {
|
||||
try {
|
||||
const result = await compressImage(file)
|
||||
this.$emit('change', result)
|
||||
} catch (error) {
|
||||
this.$message.error(error)
|
||||
}
|
||||
},
|
||||
|
||||
@ -92,7 +94,6 @@ export default {
|
||||
// 删除图片
|
||||
deleteImg() {
|
||||
this.$emit('change', '')
|
||||
this.file = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -92,4 +92,50 @@ export const getParentWithClass = (el, className) => {
|
||||
return getParentWithClass(el.parentNode, className)
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// 压缩图片
|
||||
export const compressImage = (file, options = {}) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const fileType = file.type
|
||||
let {
|
||||
maxWidth = 1200,
|
||||
maxHeight = 1200,
|
||||
quality = 0.8,
|
||||
mimeType = ''
|
||||
} = options
|
||||
const reader = new FileReader()
|
||||
reader.onload = event => {
|
||||
// 不处理gif格式
|
||||
if (/\/gif$/.test(fileType)) {
|
||||
return resolve(event.target.result)
|
||||
}
|
||||
mimeType = mimeType || fileType
|
||||
const img = new Image()
|
||||
img.onload = () => {
|
||||
// 计算新尺寸,保持宽高比
|
||||
let width = img.width
|
||||
let height = img.height
|
||||
if (width > maxWidth || height > maxHeight) {
|
||||
const ratio = Math.min(maxWidth / width, maxHeight / height)
|
||||
width = Math.floor(width * ratio)
|
||||
height = Math.floor(height * ratio)
|
||||
}
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = width
|
||||
canvas.height = height
|
||||
const ctx = canvas.getContext('2d')
|
||||
ctx.drawImage(img, 0, 0, width, height)
|
||||
resolve(canvas.toDataURL(mimeType, quality))
|
||||
}
|
||||
img.onerror = function() {
|
||||
reject(new Error('图片加载失败'))
|
||||
}
|
||||
img.src = event.target.result
|
||||
}
|
||||
reader.onerror = function() {
|
||||
reject(new Error('文件读取失败'))
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user