微信小程序开发,如何通过JavaScript获取img的原始尺寸
在前端开发中,我们几乎不需要获取img的原始尺寸,因为只要知道图片的宽和高,就会根据图片进行渲染到最佳比例。但是在开发微信小程序时,它的图片标签有一个默认的高度,所以你的图片很可能被压缩变形了,所以你需要获取原始图片大小并设置图片的宽度和高度。
微信小程序获取原始图片尺寸的方法
<view style="width:100%;" > <image bindload="loadSuccess" style="width:{{imageWidth}}px; height:{{imageHeight}}px"></image> </view> //js Page({ data: { imageHeight: 0, imageWidth: 0 }, loadSuccess(e){ const { detail: {width, height} } = e // // 这里获取到的就是图片原始尺寸 this.setData({ imageWidth: width, imageHeight:height }) } })
wx.getImageInfo
该方法为wx.getImageInfo,微信官方文档需要添加公司域名并在服务器端验证接口。这相当复杂,不推荐。
如何在浏览器中获取图片大小
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>img原始尺寸获取</title> <style> .image { /* height: 20px; 这种写法没什么卵用 */ } </style> </head> <body> <img class="image" referrerpolicy="no-referrer" style="width: 300px;"> <script> // 1. 获取DOM元素的渲染尺寸 const img = document.querySelector('.image'); console.log(img.style.width) // 300px 获取到字符串 console.log(img.style.height) // 如果在标签行内样式没有设置 无法获取到 // 2. 直接获取DOM元素的width和height属性 console.log(img.width) // 300 获取到的数字类型 console.log(img.height) // 533 可以获取到元素的渲染高度 // 3. naturalWidth / naturalHeight (适用于Firefox/IE9/Safari/Chrome/Opera浏览器) console.log('naturalWidth:', img.naturalWidth) // naturalWidth: 412 console.log('naturalHeight:', img.naturalHeight) // naturalHeight: 732 // 4. 使用Image()对象异步获取图片原始尺寸 function getImageInfo(url) { return new Promise((resolve, reject) => { let image = new Image(); image.onload = () => { resolve({ width: image.width, height: image.height }) } image.onerror = () => { reject(new Error('image load error')) } image.src = url; }) } (async () => { let size = await getImageInfo('https://image-static.segmentfault.com/193/916/1939169050-641cff9f16cdc_fix732') console.log(size) // {width: 412, height: 732} })() // 终极兼容写法 (首先检测浏览器是否支持img.naturalWidth,如果支持直接获取,不支持使用4.Image()对象获取) async function getImageSize(img) { if (img.naturalWidth) { return { width: img.naturalWidth, height: img.naturalHeight } } else { return await getImageInfo(img.src) } } </script> </body> </html>
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。