Search code examples
gatsby

Gatsby - use art direction for static images


Is it possible to use withArtDirection for static images in Gatsby?

I want to generate picture tags such as the following. Static file paths will go into the src and the srcset attributes.

<picture>
  <source media="(max-width: 799px)" srcset="elva-480w-close-portrait.jpg">
  <source media="(min-width: 800px)" srcset="elva-800w.jpg">
  <img src="elva-800w.jpg" alt="Chris standing up holding his daughter Elva">
</picture>

In the official document, there is an example of using withArtDirection for dynamic images, but there seems to be no examples for static images.


Solution

  • In the official document, there is an example of using withArtDirection for dynamic images, but there seems to be no examples for static images.

    I doesn't because withArtDirection is a helper function that works with gatsbyImageData (a node that GraphQL generates along with Gatsby for the static assets):

    There are a number of utility functions to help you work with gatsbyImageData objects. We strongly recommend that you do not try to access the internals of these objects directly, as the format could change.

    Since you don't have gatsbyImageData because the asset is not locally analyzed, you can't use it.

    The same applies to other helper functions such as getSrc, getImage or getSrcSet.

    A similar approach could be done loading one image or the other based on the viewport width or using CSS to display one image or the other, similar to what withArtDirection does.