JavaScript怎么实现获取img的原始尺寸

其他教程   发布日期:2024年10月30日   浏览次数:459

本篇内容主要讲解“JavaScript怎么实现获取img的原始尺寸”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“JavaScript怎么实现获取img的原始尺寸”吧!

在前端开发中我们几乎不需要获取img的原始尺寸,因为只要你不刻意设置图片的宽高它都会按照最佳比例渲染。但是在微信小程序开发时,它的image标签有一个默认高度,这样你的图片很可能出现被压缩变形的情况,所以就需要获取到图片的原始尺寸对image的宽高设置。

微信小程序获取image原始尺寸的方法

  1. <view >
  2. <image src="https://sf3-ttcdn-tos.pstatp.com/img/mosaic-legacy/3796/2975850990~300x300.image" bindload="loadSuccess" ></image>
  3. </view>
  1. //js
  2. Page({
  3. data: {
  4. imageHeight: 0,
  5. imageWidth: 0
  6. },
  7. loadSuccess(e){
  8. const { detail: {width, height} } = e // // 这里获取到的就是图片原始尺寸
  9. this.setData({
  10. imageWidth: width,
  11. imageHeight:height
  12. })
  13. }
  14. })

wx.getImageInfo

方法是wx.getImageInfo,微信官方文档 这个需要添加业务域名,服务端做接口验证。比较繁琐不推荐。

浏览器中获取图片尺寸的方法

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>img原始尺寸获取</title>
  8. <style>
  9. .image {
  10. /* height: 20px; 这种写法没什么卵用 */
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <img class="image" referrerpolicy="no-referrer" src="https://image-static.segmentfault.com/193/916/1939169050-641cff9f16cdc_fix732"
  16. >
  17. <script>
  18. // 1. 获取DOM元素的渲染尺寸
  19. const img = document.querySelector('.image');
  20. console.log(img.style.width) // 300px 获取到字符串
  21. console.log(img.style.height) // 如果在标签行内样式没有设置 无法获取到
  22. // 2. 直接获取DOM元素的width和height属性
  23. console.log(img.width) // 300 获取到的数字类型
  24. console.log(img.height) // 533 可以获取到元素的渲染高度
  25. // 3. naturalWidth / naturalHeight (适用于Firefox/IE9/Safari/Chrome/Opera浏览器)
  26. console.log('naturalWidth:', img.naturalWidth) // naturalWidth: 412
  27. console.log('naturalHeight:', img.naturalHeight) // naturalHeight: 732
  28. // 4. 使用Image()对象异步获取图片原始尺寸
  29. function getImageInfo(url) {
  30. return new Promise((resolve, reject) => {
  31. let image = new Image();
  32. image.onload = () => {
  33. resolve({
  34. width: image.width,
  35. height: image.height
  36. })
  37. }
  38. image.onerror = () => {
  39. reject(new Error('image load error'))
  40. }
  41. image.src = url;
  42. })
  43. }
  44. (async () => {
  45. let size = await getImageInfo('https://image-static.segmentfault.com/193/916/1939169050-641cff9f16cdc_fix732')
  46. console.log(size) // {width: 412, height: 732}
  47. })()
  48. // 终极兼容写法 (首先检测浏览器是否支持img.naturalWidth,如果支持直接获取,不支持使用4.Image()对象获取)
  49. async function getImageSize(img) {
  50. if (img.naturalWidth) {
  51. return {
  52. width: img.naturalWidth,
  53. height: img.naturalHeight
  54. }
  55. } else {
  56. return await getImageInfo(img.src)
  57. }
  58. }
  59. </script>
  60. </body>
  61. </html>

以上就是JavaScript怎么实现获取img的原始尺寸的详细内容,更多关于JavaScript怎么实现获取img的原始尺寸的资料请关注九品源码其它相关文章!