Table of Contents
Pure CSS to achieve 3D rotation of elements
Use Javascript to realize the mouse-following 3D rotation effect
控制 X 方向的移动
控制 Y 方向的移动
结合 X、Y 方向的移动
设置平滑出入
Home Web Front-end CSS Tutorial Cleverly use CSS to realize the mouse-following 3D rotation effect, making the interaction more vivid!

Cleverly use CSS to realize the mouse-following 3D rotation effect, making the interaction more vivid!

Sep 06, 2022 am 10:34 AM
css mouse follow

This article will introduce to you how to use CSS to achieve an interesting mouse-following 3D rotation effect, making the interaction more vivid. I hope it will be helpful to everyone!

Cleverly use CSS to realize the mouse-following 3D rotation effect, making the interaction more vivid!

Today, a group of friends asked a question, how to implement the mouse following interaction effect as shown below:

A brief analysis shows that this interactive effect mainly has two cores:

  • With the help of CSS 3D capabilities

  • The rotation of elements requires and Combined with the movement of the mouse

This article will describe how to use pure CSS to achieve similar interactive effects, and how to quickly restore the above effects by binding mouse events with JavaScript. [Recommended learning: css video tutorial]

Pure CSS to achieve 3D rotation of elements

How to implement it without JavaScript, just CSS What about a similar 3D rotation effect?

A little trick called positive and negative rotation cancellation or positive and negative rotation cancellation will be used here. Well, the name is very strange, it seems like a mathematical concept.

In animation, rotation is a very commonly used attribute.

{
  transform: rotate(90deg);
}
Copy after login

What will happen if we add rotation in different directions to elements at different levels?

First assume the scenario, we have such a layer of HTML structure:

<div>
    <div>
        <div>正负旋转相消3D动画</div>
    </div>
</div>
Copy after login

The style is as follows:

.content is our main content. Okay, now imagine that if the parent element .rotate performs a forward linear 360° rotation, the outermost parent element .reverseRotate What will be the effect of reverse linear 360° rotation?

The CSS code is as follows:

.rotate {
    animation: rotate 5s linear infinite;
}
.reverseRotate {
    animation: reverseRotate 5s linear infinite;
}
@keyframes rotate {
    100% {
        transform: rotate(360deg);
    }
}
@keyframes reverseRotate {
    100% {
        transform: rotate(-360deg);
    }
}
Copy after login

We can get such an animation (note that the picture below is a GIF, not a PNG):

magic! Because one rotates forward and the other reversely, and the easing function is the same, the entire .content still looks stationary! Note that it is very important that the entire .content is still.

Some readers will curse when they see this. Author, you are a retarded person. If you stop, won’t there be no animation? Where did you get your animation skills?

Don’t worry! Although it looks stationary, both elements of the ancestor are actually rotating! This may appear to be a calm effect, but underneath it is actually an undercurrent. Using the developer tools to select the outermost ancestor element is like this:

In this case, let’s continue to think about it. If I add some other elements to a parent element that is rotated, What will be the effect of the animation? It’s exciting to think about.

First, let’s add CSS 3D transformation to these elements:

div {
    transform-style: preserve-3d;
    perspective: 100px;
}
Copy after login

Then, try to modify the above rotation animation and add an additional rotateX to the inner rotation:

@keyframes rotate {
    0% {
        transform: rotateX(0deg) rotateZ(0deg);
    }
    50% {
        transform: rotateX(40deg) rotateZ(180deg);
    }
    100% {
        transform: rotateX(0deg) rotateZ(360deg);
    }
}
Copy after login

The effect is as follows:

Wow, you need to understand it carefully here. Since the content .content layer is static but actually the two outer layers are rotating, by setting additional rotateX(40deg), it is equivalent to superimposing one more animation. Since The forward and reverse rotations are offset, and the entire animation can only see the rotated rotateX(40deg) animation, which produces the above effect.

In this way, without JavaScript intervention, we simulate the 3D effect shown in the title picture. Of course, this alone is not enough to link with the user. If it must be combined with mouse movement, we will need some assistance from JavaScript.

Use Javascript to realize the mouse-following 3D rotation effect

Our goal is to achieve such an animation effect:

Here, we actually have two core elements:

  • Mouse activity area

  • The rotating object itself

The movement of the mouse within the mouse active area will affect the 3D rotation of the rotating object itself, and the direction of rotation can actually be decomposed into the X-axis direction and the Y-axis direction. .

Let’s take a look, assuming our HTML structure is as follows:

    <div></div>
Copy after login

Get such a graphic:

这里,body 的范围就是整个鼠标可活动区域,也是我们添加鼠标的 mousemove 事件的宿主 target,而 #element 就是需要跟随鼠标一起转动的旋转物体本身。

因为整个效果是需要基于 CSS 3D 的,我们首先加上简单的 CSS 3D 效果:

body {
    width: 100vw;
    height: 100vh;
    transform-style: preserve-3d;
    perspective: 500px;
}

div {
    width: 200px;
    height: 200px;
    background: #000;
    transform-style: preserve-3d;
}
Copy after login

效果如下:

没有什么不一样。这是因为还没有添加任何的 3D 变换,我们给元素添加 X、Y 两个方向的 rotate() 试一下(注意,这里默认的旋转圆心即是元素中心):

div {
     transform: rotateX(15deg) rotateY(30deg);
}
Copy after login

效果如下,是有那么点意思了:

好,接下来,我们的目标就是通过结合 mouseover 事件,让元素动起来。

控制 X 方向的移动

当然,为了更加容易理解,我们把动画拆分为 X、Y 两个方向上的移动。首先看 X 方向上的移动:

Cleverly use CSS to realize the mouse-following 3D rotation effect, making the interaction more vivid!

这里,我们需要以元素的中心为界:

  • 当鼠标在中心右侧连续移动,元素绕 Y 轴移动,并且值从 0 开始,越来越大,范围为(0, +∞)deg

  • 反之,当鼠标在中心左侧连续移动,元素绕 Y 轴移动,并且值从 0 开始,越来越小,范围为(-∞, 0)deg

这样,我们可以得到这样一个公式:

rotateY = (鼠标 x 坐标 - 元素左上角 x 坐标 - 元素宽度的一半)deg

通过绑定 onmousemove 事件,我们尝试一下:

const mouseOverContainer = document.getElementsByTagName("body")[0];
const element = document.getElementById("element");

mouseOverContainer.onmousemove = function(e) {
  let box = element.getBoundingClientRect();
  let calcY = e.clientX - box.x - (box.width / 2);
    
  element.style.transform  = "rotateY(" + calcY + "deg) ";
}
Copy after login

效果如下:

Cleverly use CSS to realize the mouse-following 3D rotation effect, making the interaction more vivid!

好吧,旋转的太夸张了,因此,我们需要加一个倍数进行控制:

const multiple = 20;
const mouseOverContainer = document.getElementsByTagName("body")[0];
const element = document.getElementById("element");

mouseOverContainer.onmousemove = function(e) {
  let box = element.getBoundingClientRect();
  let calcY = (e.clientX - box.x - (box.width / 2)) / multiple;
    
  element.style.transform  = "rotateY(" + calcY + "deg) ";
}
Copy after login

通过一个倍数约束后,效果好了不少:

控制 Y 方向的移动

同理,我们利用上述的方式,同样可以控制 Y 方向上的移动:

const multiple = 20;
const mouseOverContainer = document.getElementsByTagName("body")[0];
const element = document.getElementById("element");

mouseOverContainer.onmousemove = function(e) {
  let box = element.getBoundingClientRect();
  let calcX = (e.clientY - box.y - (box.height / 2)) / multiple;
    
  element.style.transform  = "rotateX(" + calcX + "deg) ";
};
Copy after login

效果如下:

当然,在这里,我们会发现方向是元素运动的方向是反的,所以需要做一下取反处理,修改下 calcX 的值,乘以一个 -1 即可:

let calcX = (e.clientY - box.y - (box.height / 2)) / multiple * -1;
Copy after login

结合 X、Y 方向的移动

OK,到这里,我们只需要把上述的结果合并一下即可,同时,上面我们使用的是 onmousemove 触发每一次动画移动。现代 Web 动画中,我们更倾向于使用 requestAnimationFrame 去优化我们的动画,确保每一帧渲染一次动画即可。

完整的改造后的代码如下:

const multiple = 20;
const mouseOverContainer = document.getElementsByTagName("body")[0];
const element = document.getElementById("element");

function transformElement(x, y) {
  let box = element.getBoundingClientRect();
  let calcX = -(y - box.y - (box.height / 2)) / multiple;
  let calcY = (x - box.x - (box.width / 2)) / multiple;
  
  element.style.transform  = "rotateX("+ calcX +"deg) "
                        + "rotateY("+ calcY +"deg)";
}

mouseOverContainer.addEventListener('mousemove', (e) => {
  window.requestAnimationFrame(function(){
    transformElement(e.clientX, e.clientY);
  });
});
Copy after login

至此,我们就能简单的实现题图所示的鼠标跟随 3D 旋转动效:

设置平滑出入

现在,还有最后一个问题,就是当我们的鼠标离开活动区域时,元素的 transform 将停留在最后一帧,正确的表现应该是复原到原状。因此,我们还需要添加一些事件监听做到元素的平滑复位。

通过一个 mouseleave 事件配合元素的 transition 即可。

div {
    // 与上述保持一致...
    transition: all .1s;
}
Copy after login
mouseOverContainer.addEventListener('mouseleave', (e) => {
  window.requestAnimationFrame(function(){
    element.style.transform = "rotateX(0) rotateY(0)";
  });
});
Copy after login

至此,我们就可以完美的实现平滑出入,整体效果最终如下:

完整的代码,你可以戳这里:CodePen Demo -- CSS 3D Rotate With Mouse Move

(学习视频分享:web前端

The above is the detailed content of Cleverly use CSS to realize the mouse-following 3D rotation effect, making the interaction more vivid!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

How to resize bootstrap How to resize bootstrap Apr 07, 2025 pm 03:18 PM

To adjust the size of elements in Bootstrap, you can use the dimension class, which includes: adjusting width: .col-, .w-, .mw-adjust height: .h-, .min-h-, .max-h-

See all articles