Adding a scroll-based CSS animation
With locomotive-scroll it's very easy to add a CSS progress to a specific DOM element. First let's start by adding some required HTML attributes to our block :
data-scroll=> Enable viewport detection on an element.data-scroll-css-progress=> Will add a CSS variable--progressto the element. This variable represents the current progress of the element and ranges between0and1.
<section class="c-poster" data-scroll data-scroll-css-progress>
{# ... #}
</section>
We can then use it easily within our _poster.scss file. Let's do something cool with the image!
// ...
.c-poster_image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
transform: translate3d(0,0,0) scale(calc(1 + (1 - var(--progress)) * 0.5));
}
Focus point
To enhance our animation, let's adjust the transform-origin of our animation. Fortunately, our image data includes a focus_point with x and y values. These values will help ensure that the scaling effect is centered around the subject in the image.
One effective approach is to pass this data as inline CSS variables.
<section class="c-poster" data-scroll data-scroll-css-progress>
{# ... #}
{# Styles `attr` for a custom animation based on the focus point #}
{% include "@snippets/image.twig" with {
classes: 'c-poster_image',
modifiers: '-cover',
src: poster.img.src,
width: poster.img.width,
height: poster.img.height,
attr: 'style="--focus-point-x: ' ~ poster.img.focus_point.x ~ '; --focus-point-y: ' ~ poster.img.focus_point.y ~ ';"'
} only %}
</section>
The final step is to set the transform-origin property based on the CSS variables we've just passed.
// ...
.c-poster_image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
transform: translate3d(0,0,0) scale(calc(1 + (1 - var(--progress)) * 0.5));
transform-origin: var(--focus-point-x, "center") var(--focus-point-y, "center");
}
In our case, we could have easily managed the focus point with transform-origin: center top;. However, let's consider a scenario where another image requires a focus point that cannot be achieved using the center, top, bottom, left, or right shortcuts.
Next up, the products listing!