旋转的错觉
像这种旋转动画怎么实现呢?
- 首先先实现布局:布局的话可以采用 Grid 布局,通过给不同元素设置不同的分区实现下图
.container {
width: 300px;
height: 300px;
margin: 0 auto;
margin-top: 100px;
display: grid;
grid-template-rows: repeat(3, 1fr);
grid-template-columns: repeat(3, 1fr);
grid-template:
'a a b'
'c e b'
'c d d';
gap: 5px;
.item {
overflow: hidden;
border: 1px solid #ddd;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
&:nth-of-type(1) {
grid-area: a;
}
&:nth-of-type(2) {
grid-area: b;
}
&:nth-of-type(3) {
grid-area: c;
}
&:nth-of-type(4) {
grid-area: d;
}
&:nth-of-type(5) {
grid-area: e;
}
}
}
@keyframes rotation {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
- 再进行动画处理,这里动画分两部分处理
- 一是外层容器顺时针旋转
- 二是里层的图片逆时针旋转
.container {
animation: rotation 10s infinite linear;
.item {
img {
width: 100%;
height: 100%;
object-fit: cover;
animation: rotation 10s infinite linear reverse;
}
}
}
@keyframes rotation {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
经过上面两步会发现图片旋转是实现了,是会有白边。这是因为图片太小,在旋转过程中不够铺满外层容器,处理方法就是放大图片就行喽。
img {
width: 210%;
height: 210%;
object-fit: cover;
animation: rotation 10s infinite linear reverse;
}
完整代码如下:
import React from 'react';
import img1 from './image/3.jpg';
import img2 from './image/5.jpg';
import img3 from './image/2.jpg';
import img4 from './image/4.jpg';
import img5 from './image/1.jpg';
import './index.less'
export default function index() {
return (
<div className="container">
<div className="item">
<img src={img1} alt="" />
</div>
<div className="item">
<img src={img2} alt="" />
</div>
<div className="item">
<img src={img3} alt="" />
</div>
<div className="item">
<img src={img4} alt="" />
</div>
<div className="item">
<img src={img5} alt="" />
</div>
</div>
);
}
.container {
width: 300px;
height: 300px;
margin: 0 auto;
margin-top: 100px;
display: grid;
grid-template-rows: repeat(3, 1fr);
grid-template-columns: repeat(3, 1fr);
grid-template:
'a a b'
'c e b'
'c d d';
gap: 5px;
animation: rotation 10s infinite linear;
.item {
overflow: hidden;
border: 1px solid #ddd;
display: flex;
justify-content: center;
align-items: center;
img {
width: 210%;
height: 210%;
object-fit: cover;
animation: rotation 10s infinite linear reverse;
}
&:nth-of-type(1) {
grid-area: a;
}
&:nth-of-type(2) {
grid-area: b;
}
&:nth-of-type(3) {
grid-area: c;
}
&:nth-of-type(4) {
grid-area: d;
}
&:nth-of-type(5) {
grid-area: e;
}
}
}
@keyframes rotation {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}