Using Storybloks focus point for css background images

We wanted to use Storybloks focus point feature for images but needed to use them as the CSS property background-position. We produced this helper function to deal with this in out Nuxt app. Hope it helps anyone struggling.

/**
 * Takes Storyblok url and focus point to generate a background position for images
 *
 * @param url image url from Storyblok
 * @param focus image focal point from Storyblok
 * @returns {string} string used for css background position
 */
export function storyblokImageFocalPoint(url, focus) {
  if (!url || !focus) return null
  const [imageWidth, imageHeight] = url.split('/')[5].split('x')
  const [focusWidth, focusHeight] = focus.split(':')[0].split('x')
  const percentageWidth = Math.round((focusWidth / imageWidth) * 100)
  const percentageHeight = Math.round((focusHeight / imageHeight) * 100)
  return `${percentageWidth}% ${percentageHeight}%`
}
1 Like

Hello @nhensh,

thanks for sharing that with our community! Feel free to check our Discord server out: Storyblok

Best regards
Hannes

Hello @nhensh,

my colleagues are very grateful for sharing that script with the community and asked kindly if you could place it in a repository that we can link to our list GitHub - storyblok/awesome-storyblok: A curated list of awesome things related to Storyblok CMS. 😏

Best regards
Hannes