Using Sanity Hotspot with GatsbyImage for Image Cropping
Great question! Yes, you can absolutely use Sanity's hotspot data with GatsbyImage using CSS object-position. Let me break down what those values mean and how to use them.
Understanding Hotspot Values
The hotspot values you're seeing are normalized coordinates (0 to 1) representing positions and dimensions as percentages:
x: Horizontal position of the hotspot center (0 = left edge, 1 = right edge, 0.5 = center)y: Vertical position of the hotspot center (0 = top edge, 1 = bottom edge, 0.5 = center)width: Width of the hotspot area as a fraction of the total image widthheight: Height of the hotspot area as a fraction of the total image height
So in your example, x: 0.406 and y: 0.483 means the hotspot is positioned at roughly 40.6% from the left and 48.3% from the top of the image.
Converting to CSS object-position
Here's a helper function to convert Sanity hotspot data to CSS object-position:
function getObjectPosition(hotspot) {
if (!hotspot || !hotspot.x || !hotspot.y) {
return "center center";
}
return `${hotspot.x * 100}% ${hotspot.y * 100}%`;
}Using with GatsbyImage
You can apply this to your GatsbyImage component using the style or imgStyle prop:
import { GatsbyImage, getImage } from "gatsby-plugin-image"
const MyComponent = ({ image }) => {
const gatsbyImage = getImage(image)
const objectPosition = getObjectPosition(image.hotspot)
return (
<GatsbyImage
image={gatsbyImage}
alt={image.alt}
imgStyle={{
objectFit: "cover",
objectPosition: objectPosition
}}
/>
)
}For your square crop use case, this will ensure that when the image is cropped to a square, the area you selected in Sanity Studio remains visible and centered.
Querying Hotspot Data
Make sure you're querying the hotspot data in your GraphQL query:
query {
sanityYourType {
image {
hotspot {
x
y
height
width
}
asset {
gatsbyImageData(width: 400, height: 400, fit: FILLMAX)
}
}
}
}This approach is mentioned in Sanity's documentation on using hotspot with GatsbyImage and is a reliable way to handle focal points when the image URL builder doesn't automatically apply them in your frontend framework.
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.