Параллакс с объектами

Параллакс с объектами

В этом видео я расскажу, как создать интересный параллакс для объектов по движению курсора мыши

Описание
Видеоинструкция по подключению
Инструкция с копированием шаблона к себе
ID шаблона:
38932885
Создаём новую страницу на сайте
Шаг 1
Скроллим в самый низ и нажимаем кнопку «Указать ID шаблона»
Шаг 2
В графе указываем номер шаблона (он указан в начале инструкции), нажимаем кнопку «Выбрать»
Шаг 3
Пошаговая инструкция с подключением кода
В Zero-блоке создаём необходимый объект с которым будем работать, к примеру шейп и присваиваем ему класс shape-config1. Я создам сразу 3 таких объекта, но с разными классами, чтобы можно было управлять ими индивидуально: shape-config1, shape-config2, shape-config3
Шаг 1
В настройках Zero-блока, где находятся объекты, указываем класс uc-image-parallax
Шаг 2
Ниже создаём блок t123 и добавляем код
Шаг 3
<!--Параллакс с объектами-->
<!--https://mt-webdesign.ru/parallax-with-objects-->
<style>
/*Перечисляем объекты*/
.shape-config1, .shape-config2, .shape-config3 {
transition: transform 0.3s ease-out;
transform-style: preserve-3d;
}
</style>
<script>
class ShapeConfig {
constructor(maxRotation, attractionFactor, exitSmoothness) {
this.maxRotation = maxRotation;
this.attractionFactor = attractionFactor;
this.exitSmoothness = exitSmoothness;
}
}
// Указываем анимацию для объектов
const shapeConfigs = {
'shape-config1': new ShapeConfig(-30, 0.1, 0.15), /* Первая цифра - определяет угол наклона в градусах, Вторая цифра - отвечает за область взаимодействия курсора и объекта, Третья - отвечает за плавность анимации*/
'shape-config2': new ShapeConfig(10, 0.1, 0.15), /* Первая цифра - определяет угол наклона в градусах, Вторая цифра - отвечает за область взаимодействия курсора и объекта, Третья - отвечает за плавность анимации*/
'shape-config3': new ShapeConfig(-15, 0.1, 0.15) /* Первая цифра - определяет угол наклона в градусах, Вторая цифра - отвечает за область взаимодействия курсора и объекта, Третья - отвечает за плавность анимации*/
};
function handleMouseMove(e, shapes, ucBlock) {
const mouseX = e.clientX;
const mouseY = e.clientY;
const blockRect = ucBlock.getBoundingClientRect();
const blockCenterX = blockRect.left + blockRect.width / 2;
const blockCenterY = blockRect.top + blockRect.height / 2;
shapes.forEach((shape) => {
const shapeRect = shape.getBoundingClientRect();
const shapeCenterX = shapeRect.left + shapeRect.width / 2;
const shapeCenterY = shapeRect.top + shapeRect.height / 2;
const deltaX = shapeCenterX - mouseX;
const deltaY = shapeCenterY - mouseY;
const angleX = deltaX / (blockRect.width / 2);
const angleY = deltaY / (blockRect.height / 2);
const shapeClass = Array.from(shape.classList).find(cls => cls.startsWith('shape-config'));
const shapeConfig = shapeConfigs[shapeClass];
const rotationX = angleY * shapeConfig.maxRotation;
const rotationY = -angleX * shapeConfig.maxRotation;
const rotationZ = -angleX * shapeConfig.maxRotation;
const attractionX = (mouseX - shapeCenterX) * shapeConfig.attractionFactor;
const attractionY = (mouseY - shapeCenterY) * shapeConfig.attractionFactor;
shape.style.transform = `translate(${attractionX}px, ${attractionY}px) rotateX(${rotationX}deg) rotateY(${rotationY}deg) rotateZ(${rotationZ}deg)`;
});
}
function smoothExit(shapes) {
shapes.forEach((shape) => {
const shapeClass = Array.from(shape.classList).find(cls => cls.startsWith('shape-config'));
const exitSmoothness = shapeConfigs[shapeClass].exitSmoothness;
const attractionX = parseFloat(shape.style.transform.split('(')[1].split('px, ')[0]);
const attractionY = parseFloat(shape.style.transform.split('px, ')[1].split('px)')[0]);
shape.style.transform = `translate(${attractionX * (1 - exitSmoothness)}px, ${attractionY * (1 - exitSmoothness)}px)`;
if (Math.abs(attractionX) > 0.1 || Math.abs(attractionY) > 0.1) {
requestAnimationFrame(() => smoothExit(shapes));
} else {
shape.style.transform = 'translate(0, 0)';
}
});
}
// Добавляем проверку на ширину окна перед запуском скрипта
function initializeParallax() {
const windowWidth = window.innerWidth;
if (windowWidth >= 768) {
document.querySelectorAll('.uc-image-parallax').forEach(ucBlock => {
const shapes = ucBlock.querySelectorAll('.shape-config1, .shape-config2, .shape-config3');
ucBlock.addEventListener('mousemove', (e) => {
handleMouseMove(e, shapes, ucBlock);
});
ucBlock.addEventListener('mouseleave', () => {
smoothExit(shapes);
});
});
}
}
// Запускаем скрипт при загрузке страницы
window.addEventListener('load', initializeParallax);
// Запускаем скрипт также при изменении размеров окна
window.addEventListener('resize', initializeParallax);
</script>
Более подробные настройки, возможности взаимодействия и подключение в видео
Другие модификации
Эффект следа из изображений
Tilda
Анимация градиента на тексте
Tilda