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 }
标签:canvas,img,naturalHeight,压缩,height,width,let,js From: https://www.cnblogs.com/87duan/p/17893706.html