利用css3和js实现旋转木马图片小demo

时间:2022-06-20 19:25:55

先看效果图:

利用css3和js实现旋转木马图片小demo

上源码

html代码

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="./index.css">
</head> <body>
<div class="box">
<img src="./img/1.png" alt="">
<img src="./img/2.png" alt="">
<img src="./img/3.png" alt="">
<img src="./img/4.png" alt="">
<img src="./img/5.png" alt="">
<img src="./img/6.png" alt="">
<img src="./img/1.png" alt="">
<img src="./img/2.png" alt="">
<img src="./img/3.png" alt="">
<img src="./img/4.png" alt="">
<img src="./img/5.png" alt="">
<img src="./img/6.png" alt="">
</div>
<script src="./jquery-3.3.1.js"></script>
<script src="./index.js"></script>
</body> </html>

css代码

*{
margin:0;
padding:0;
}
html,body{
width:100%;
height:100%;
background-image:radial-gradient(circle at center center,rgba(244,23,234,0.2),rgba(0,0,0));
background-color:#000;
overflow: hidden;
perspective: 1000px;
}
.box{
position: relative;
width:120px;
height:180px;
margin:200px auto;
transform-style:preserve-3d;
}
.box img{
position: absolute;
width:100%;
height:100%;
-webkit-box-reflect: below 10px -webkit-linear-gradient(top,rgba(0,0,0,0) 40%,rgba(0,0,0,0.5) 100%); /*倒影*/
}

js(jquery)代码

window.onload = function () {
var img = $('img');
var len = img.length;
var deg = 360 / len;
for (var i = 0; i < len; i++) {
$('img').eq(i).css({
'transform': 'rotateY(' + i * deg + 'deg) translateZ(300px)',
'transition': 'transform 0.5s linear ' + (len - 1 - i) * 0.1 + 's'
}) //实现 刚开始的发牌效果。
};
bindEvent();
}
function bindEvent() {
var box = $('.box');
var body = $('body');
var lastX, lastY, nowX, nowY, disX, disY;
var roX = 0, roY = 0;
var timer;
body.on('mousedown', function (e) {
clearInterval(timer);
lastX = e.clientX;
lastY = e.clientY;
body.on('mousemove', function (e) {
nowX = e.clientX;
nowY = e.clientY; disX = nowX - lastX;
disY = nowY - lastY; roX -= disY * 0.2;
roY += disX * 0.2; roX = roX % 360;
roY = roY % 360; box.css({
'transform': 'rotateX(' + roX + 'deg) rotateY(' + roY + 'deg)',
}); lastX = nowX;
lastY = nowY;
})
return false;
}).on('mouseup', function () { body.off('mousemove');
// 以下是缓冲
timer = setInterval(function () {
disX *= 0.95;
disY *= 0.95;
roX -= disY * 0.5;
roY += disX * 0.5; roX = roX % 360;
roY = roY % 360; box.css({
'transform': 'rotateX(' + roX + 'deg) rotateY(' + roY + 'deg)',
}); if (Math.abs(disX) < 0.01 && Math.abs(disY) < 0.01) {
clearInterval(timer);
} }, 20);
});
}