内联 SVG 中的响应式图像

Responsive images in inline SVG

我试图找到一个例子或答案,但没能找到。

我们优化图像的方式,以便在不需要时不必加载不必要的大图像,可以像下面的示例一样完成:

<img src="http://localhost:8888/example.jpg" alt="sample 1" srcset="http://localhost:8888/example-1024x1024.jpg 1000w, http://localhost:8888/example-300x300.jpg 300w, http://localhost:8888/example-150x150.jpg 150w, http://localhost:8888/example-768x768.jpg 768w" sizes="(max-width: 1000px) 100vw, 1000px">

所以我的问题是,是否也可以用相同的方式或以其他方式对内联 SVG 中使用的图像进行优化。

SVG 中使用的图像,如本例所示:

<svg role="img" width="100%" height="100%">
  <title>Ocean wave</title>
  <desc>Ocean wave in crystal clear blue water.</desc>
  <defs>
    <filter id="blur">
      ...
    </filter>
  </defs>
  <image href="img/image.jpg" width="100%" height="100%" preserveAspectRatio="xMidYMid slice"></image>
</svg>

使用 <foreignObject> 而不是 <image> 似乎可以解决问题,因为这使您可以在 SVG 中使用任何类型的 HTML 元素。

<svg role="img" width="100%" height="100%">
  <title>Ocean wave</title>
  <desc>Ocean wave in crystal clear blue water.</desc>
  <defs>
    <filter id="blur">
      ...
    </filter>
  </defs>
  <foreignObject width="100%" height="100%">
    <img src="img/image.jpg" alt="sample 1" srcset="http://localhost:8888/example-1024x1024.jpg 1000w, http://localhost:8888/example-300x300.jpg 300w, http://localhost:8888/example-150x150.jpg 150w, http://localhost:8888/example-768x768.jpg 768w" sizes="(max-width: 1000px) 100vw, 1000px">
  </foreignObject>
</svg>