css3动画与2D、3D之间的转换

应用css3中的transition(过渡动画)、@keyframes(关键帧动画)、transform(2D、3D转换)可以实现一些小的动画效果。

一、transition—过渡动画

<!DOCTYPE html>

<html>

<head>

<title>基本图像的放大缩小</title>

<meta charset="utf-8">

<style type="text/css">

#div1{

width: 200px;

height: 200px;

background: red;

transition: 1s ease 0.5s;

margin: 50px auto 0;

}

#div1:hover{

width: 400px;

height: 400px;

background: blue;

border-radius: 5%;

}

</style>

</head>

<body>

<div ></div>

</body>

</html>

这是一个基本的红色方块与蓝色方块的转换效果,transition属性实现了这两者之间的过渡。

五个属性

1、transition-property css样式的属性名称;

2、transition-duration 动画的持续时间,单位为s;

3、transition-timing-function 动画效果的函数名称,后接linear(线性变化)、ease(逐渐慢下来)、ease-in(加速)、ease-out(减速)等;

4、transition-delay 动画延迟执行的时间,单位也是s。

5、animation-play-state:paused; 暂停动画执行。

五个属性可以简写为 transition:样式 持续时间 动画效果 延迟时间;(效果没有可以不写)

二、@keyframes关键帧动画

七个属性

animation-name 帧动画名称

animation-duration 动画持续时间 (需要单位 s)

animation-timing-function 动画效果函数名称 inear、ease、ease-in、ease-out、ease-in-out

animation-delay 延迟执行动画的时间

animation-iteration-count 动画播放次数 n 次数 infinite 无限次

animation-direction 是否轮流播放 normal 正常播放 alternate 来回轮流播放

animation-fill-mode: none | forwards | backwards | both | initial | inherit; 动画完成时的状态

@keyframes 帧动画名称 { selector { styles } }selector from to / %

简写 animation:name time ease delay count direction fill-mode;中间用空格隔开。

<!DOCTYPE html>

#div1{

width: 200px;

height: 200px;

background: #ccc;

position: absolute;

left: 10px;

top: 100px;

/*animation:move 2s linear infinite;*/

animation:move 2s;

/*animation-fill-mode: forwards;*/

animation-fill-mode: backwards;

}

@keyframes move{

form{left: 10px;}

to{left: 500px;}

}

/* @keyframes move{

50% {left: 500px;}

100% {left: 10px;}

}

*/

</style>

</head>

<body>

<div ></div>

</body>

</html>

三、transform(2D、3D变换)

首先是transform-2D变换,2D变换有偏移、缩放、旋转和倾斜,每一个需要用到不同的属性值,分别为:translate、scale、rotate、skew;其中translate、scale、skew具有x轴和y轴,比如translateX(50px)表示向X轴正半轴偏移50像素,translateY(40px)表示向Y轴负半轴偏移40像素,当然,也可以合起来写:translate(50px,40px),表示同时向X轴Y轴分别偏移50和40像素,中间用逗号隔开。

transform-3D变换比2D变换每个属性都多了一个Z轴,当然需要设置transform-style:preserve-3d;才能看到3D视角效果,否则只能看到平面效果

<!DOCTYPE html>

<html>

<head>

<title>旋转</title>

<meta charset="utf-8">

<style type="text/css">

#box{

width: 300px;

height: 400px;

border: 5px solid #000;

margin: 100px auto 0;

transform-style: preserve-3d;

transform: rotateX(30deg) rotateY(-45deg) rotateZ(30deg);

}

.div1{

width: 300px;

height: 400px;

background: red;

animation: move 2s linear infinite;

}

@keyframes move{

0%{ transform: rotateX(0deg);}

25%{ transform: rotateX(90deg);}

50%{ transform: rotateX(180deg);}

75%{ transform: rotateX(270deg);}

100%{ transform: rotateX(360deg);}

}

</style>

</head>

<body>

<div ></div>

</div>

</body>

</html>