I am experimenting with creating a unique effect where two rectangular shapes, each containing text and with rounded ends, move towards each other, merge to form a single rounded rectangle as the page is scrolled down, and then separate back when scrolling up. I want these shapes to remain fixed in their position relative to the viewport during scrolling. https://i.sstatic.net/XIk6RUdc.gif
My Attempts So Far:
- I have tried using CSS translations and transformations along with JS adjustments of the border-radius properties.
- I experimented with clip-path, but it resulted in ellipse shapes instead.
- Using HTML Shapes did not work as they need to be containers for my content.
My closest success has been getting the shapes to move close together and slightly overlap. However, other attempts have led to ellipses, unnatural border-radius behavior, or lack of cohesion between the elements.
document.addEventListener('scroll', () => {
const scrollPercent = window.scrollY / (document.body.scrollHeight - window.innerHeight);
const movement = (window.innerWidth / 2 - 115) * scrollPercent;
const shape1 = document.querySelector('.shape:nth-child(1)');
const shape2 = document.querySelector('.shape:nth-child(2)');
shape1.style.transform = `translateX(${movement}px)`;
shape2.style.transform = `translateX(-${movement}px)`;
});
body {
width: 90%;
margin: 0 auto;
padding: 20px;
height: 2000px;
}
.container {
position: sticky;
top: 20px;
display: flex;
justify-content: space-between;
}
.shape {
display: flex;
justify-content: center;
align-items: center;
width: 100px;
height: 30px;
border-radius: 15px;
background-color: #000;
color: #fff;
transition: transform 0.3s ease-out;
transform: translateX(0%);
}
<body>
<div class="container">
<div class="shape" id="shape1">Shape 1</div>
<div class="shape" id="shape2">Shape 2</div>
</div>
</body>
Question: I suspect that I may need to explore clip-path further to achieve my desired effect. How can I refine my CSS and adjust my JavaScript to create the morphing effect depicted in the image above while maintaining rounded edges and ensuring coherence between the two container elements? Any suggestions or corrections regarding my current approach would be greatly appreciated. Thank you.