// url 图片地址
// w 压缩宽度
// ext 图片类型
getBase64Image (url, w, ext) {
// const _this = this
// 将图片转为base64
return new Promise((resolve, reject) => {
var image = new Image()
// 解决跨域 Canvas 污染问题
image.setAttribute('crossOrigin', 'anonymous') // 跨域
image.onload = function () {
var canvas = document.createElement('canvas')
let imgWidth = image.width
let imgHeight = image.height
if (Math.max(imgWidth, imgHeight) > w) {
if (imgWidth > imgHeight) {
canvas.width = w
canvas.height = w * imgHeight / imgWidth
} else {
canvas.height = w
canvas.width = w * imgWidth / imgHeight
}
} else {
canvas.width = imgWidth
canvas.height = imgHeight
}
console.log(canvas.width, canvas.height, 'height')
var context = canvas.getContext('2d')
context.clearRect(0, 0, canvas.width, canvas.height)
context.drawImage(image, 0, 0, canvas.width, canvas.height)
var url = canvas.toDataURL(`image/${ext}`, 0.6) // ext图片格式类型, 0.6压缩比例
resolve(url)
}
const timestamp = Date.parse(new Date())
image.src = url + '?t=' + timestamp // 加上时间戳防止缓存/跨域
})
}
js canvas图片base64压缩
最新推荐文章于 2024-05-24 09:31:27 发布