Account created on 17 June 2016, over 8 years ago
  • Front-end developer at iO 
  • Front-end developer at One Shoe 
#

Recent comments

If anybody is still looking for a solution to get the values to the frontend to use it along with object position.

The preprocess function gets the relative values of the focal point and adds a custom property in the style attribute of the image.

function theme_preprocess_responsive_image_formatter(&$variables) {
  // Load the file entity from the original image.
  $file_entity = File::load($variables['item']->get('target_id')->getValue());

  // Get the focal point crop info.
  $crop = \Drupal::service('focal_point.manager')->getCropEntity($file_entity, 'focal_point');
  if ($crop) {
    // Get the x and y position from the crop.
    $fp_abs = $crop->position();
    $x = $fp_abs['x'];
    $y = $fp_abs['y'];

    // Get the original width and height from the image.
    $width = $variables['item']->get('width')->getValue();
    $height = $variables['item']->get('height')->getValue();

    // Convert the absolute x and y positions to relative values.
    $fp_rel = \Drupal::service('focal_point.manager')->absoluteToRelative($x, $y, $width, $height);

    // Set a custom property and add to the style attribute.
    $css_var = '--focal-point-position: ' . $fp_rel['x'] . '% ' . $fp_rel['y'] . '%;';
    $variables['responsive_image']['#attributes']['style'] = $css_var;
  }
}

You can use the custom property in your css with a 50% 50% fallback.

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: var(--focal-point-position, 50% 50%);
}
Production build 0.71.5 2024