Getting focal point values from image.

Created on 28 May 2018, over 6 years ago
Updated 9 February 2024, 11 months ago

In order to get focal points to play nice with a responsive design, I need the focal point values added as data attributes to the image.

Is there a way to get the focal point values for an image? I just need the X and Y values (-1 to 1 values would be awesome, but otherwise I can calculate those fine myself, if I get the appropriate pixel values for the focal point.).

💬 Support request
Status

Fixed

Version

1.0

Component

Documentation

Created by

🇩🇰Denmark dionsj Århus

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 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