立方体跟随鼠标旋转

html部分

 

3D立方体

bottom
top
left
right
front
back

Css部分

.container {
	width: 1000px;
	margin: 0 auto;
	padding: 50px;
	text-align: center;
	position: relative;
	background-color: rgb(218, 218, 218);
}

.clearfix:after {
	content: '';
	display: block;
	clear: both;
}


/* 立方体------- */
.cube {
	width: 200px;
	height: 200px;
	/* background: gainsboro; */
	transform-style: preserve-3d;
	transform: rotateX(30deg) rotateY(30deg);
	position: relative;
	margin: 200px auto;

}

.face {
	width: 200px;
	height: 200px;
	position: absolute;
	opacity: 0.6;
	font-size: 2em;
	color: white;
	text-transform: uppercase;
	line-height: 200px;
	/* backface-visibility: hidden; */
	transition: all 1s linear;
}

.front {
	background-color: red;
	transform: translateZ(100px);
}

.back {
	background-color: green;
	transform: rotateY(180deg) translateZ(100px);
}

.left {
	background-color: blue;
	transform: rotateY(90deg) translateZ(100px);
}

.right {
	background-color: orange;
	transform: rotateY(-90deg) translateZ(100px);
}

.top {
	background-color: purple;
	transform: rotateX(90deg) translateZ(100px);
}

.bottom {
	background-color: black;
	transform: rotateX(-90deg) translateZ(100px);
}

.btn {
	border-radius: 50% 50%;
	width: 80px;
	height: 80px;
	background: #000000;
	color: white;
	border: none;
}

JavaScript部分

let container = document.querySelector('.container')
let cube = document.querySelector('.cube')

// let rotateble = false
// let k = 0.5
let x = 0;
let y = 0;
// container.addEventListener('mousemove', function (e) {
//     if (rotateble) {
//         console.log(e)
//          x += e.movementX
//          y += e.movementY
//         cube.style.transform = `rotateX(${-y}deg) rotateY(${x}deg)`
//     }
// })
//给容器添加一个监听鼠标左键按下的事件
container.addEventListener('mousedown', function () {
    //当鼠标按下的时候给容器添加监听鼠标移动事件
    this.addEventListener('mousemove',rotate)
})
//给容器添加一个监听鼠标左键抬起的事件
container.addEventListener('mouseup', function () {
    //当鼠标左键抬起的时候给容器移除监听鼠标移动事件
    this.removeEventListener('mousemove',rotate)
})
//鼠标移动事件的回掉函数

function rotate(e) {
    x += e.movementX //movementX系统监听鼠标移动两次之间的相对位移
    y += e.movementY
    cube.style.transform = `rotateX(${-y}deg) rotateY(${x}deg)`
}
//movementX
//例如系统每隔0.1s相应一次鼠标移动,movementX就是0.1s到0.2s鼠标x移动的距离

你可能感兴趣的:(JavaScript,立方体旋转)