js(canvas) 图片压缩

发布时间 2023-12-11 09:42:10作者: 87de海雷
 1 function compress(url, width, height) {
 2     return new Promise((resolve, reject) => {
 3         let img = document.createElement('img')
 4         img.onload = () => {
 5             let w = width
 6             let h = img.naturalHeight * (width / img.naturalWidth) //等比缩放
 7             if (h < height) {
 8                 w = img.naturalWidth * (height / img.naturalHeight)
 9                 h = height
10             }
11             let c = document.createElement('canvas')
12             c.width = width
13             c.height = height
14             let ctx = c.getContext('2d')
15             ctx.drawImage(img, 0, 0, w, h)
16             resolve(c.toDataURL('image/png'))
17         }
18         img.onerror = reject
19         img.src = url
20     })
21 }