img srcset,浏览器选择过大的图片

Att*_*nen 2 html dpi highdpi retina-display gatsby

这是 Gatsby 生成的图像 srcset:

<source type="image/webp" srcset="
/static/be21c7dd0d11c74c18530fc39aefa922/10917/mailboxes.webp 200w,
/static/be21c7dd0d11c74c18530fc39aefa922/21f2d/mailboxes.webp 400w,
/static/be21c7dd0d11c74c18530fc39aefa922/fdc6a/mailboxes.webp 800w,
/static/be21c7dd0d11c74c18530fc39aefa922/e7f3d/mailboxes.webp 1200w,
/static/be21c7dd0d11c74c18530fc39aefa922/faacb/mailboxes.webp 1600w,
/static/be21c7dd0d11c74c18530fc39aefa922/acdd2/mailboxes.webp 1800w" 
sizes="(max-width: 800px) 100vw, 800px">
Run Code Online (Sandbox Code Playgroud)

我的图像显示在最多 800 像素宽的容器中,所以这是我希望浏览器选择的方式:

if screenWidth > 400 then choose 800w
if screenWidth > 200 then choose 400w
else choose 200w
Run Code Online (Sandbox Code Playgroud)

但是,浏览器实际上总是选择尽可能大的图像(即使我将浏览器的大小调整为 200 宽度)。

我相信问题出在这里:

sizes="(max-width: 800px) 100vw, 800px"

应该有~3个条件,对吧?相反,只有 1 个条件。我不确定我什至能够解释这个条件试图要求浏览器做什么。

下面是我的 GraphQL 代码:

edges {
    node {
      excerpt
      fields {
        slug
        prefix
      }
      frontmatter {
        title
        tags
        cover {
          children {
            ... on ImageSharp {
              fluid(maxWidth: 800, maxHeight: 360, traceSVG: { color: "#f9ebd2" }) {
                ...GatsbyImageSharpFluid_withWebp_tracedSVG
              }
            }
          }
        }
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

该片段...GatsbyImageSharpFluid_withWebp_tracedSVG生成srcsetsizes。在文档中,我无法做任何事情来影响它们的生成方式。但是,我可能会在以后操纵它们:

<Picture fluid={fluid} />
Run Code Online (Sandbox Code Playgroud)

我应该fluid.sizes在这一点上进行操作,还是有一种不那么脏的方法来修复 srcset?

Att*_*nen 5

结果证明加载了高分辨率图像,因为我使用的是具有高 DPI 的设备。所以它按预期工作。

devicePixelRatio在选择要显示的图像时,Web 浏览器会应用其计算。例如,如果 devicePixelRatio == 2,则设备具有典型像素数量的 2 倍(相对于设备的物理宽度和到用户的物理距离)。当浏览器想要在此设备上呈现“800 像素宽”的图像时,它实际上需要 1600 像素宽的图像才能使其在这种高 DPI 显示器上看起来不错。

浏览器实际上遵循了sizes规则。改编自德里克的回答:

(max-width: 800px) 100vw   -> If viewport < 800px, use (100vw * devicePixelRatio)
800px                      -> By default use (800px * devicePixelRatio)
Run Code Online (Sandbox Code Playgroud)