淘先锋技术网

首页 1 2 3 4 5 6 7

3D魔方游戏是一款经典的智力游戏,如今通过HTML和JavaScript实现的3D魔方游戏也取得了不错的效果。以下是3D魔方游戏的HTML代码:

<!DOCTYPE html>
<html>
<head>
<title>3D魔方游戏</title>
<style>
/*CSS样式表*/
#container {
width: 200px;
height: 200px;
perspective: 600px;
}
.cube {
width: 100px;
height: 100px;
transform-style: preserve-3d;
position: relative;
animation: spin 10s linear infinite;
}
.cube .face {
position: absolute;
width: 100px;
height: 100px;
border: 2px solid black;
box-sizing: border-box;
background-color: #fff;
opacity: 0.8;
}
.cube .front {
transform: translateZ(50px);
}
.cube .back {
transform: translateZ(-50px) rotateY(180deg);
}
.cube .left {
transform: rotateY(-90deg) translateX(-50px);
transform-origin: left;
}
.cube .right {
transform: rotateY(90deg) translateX(50px);
transform-origin: right;
}
.cube .top {
transform: rotateX(-90deg) translateY(-50px);
transform-origin: top;
}
.cube .bottom {
transform: rotateX(90deg) translateY(50px);
transform-origin: bottom;
}
@keyframes spin {
0% { transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg); }
100% { transform: rotateX(360deg) rotateY(360deg) rotateZ(360deg); }
}
</style>
</head>
<body>
<div id="container">
<div class="cube">
<div class="face front"></div>
<div class="face back"></div>
<div class="face left"></div>
<div class="face right"></div>
<div class="face top"></div>
<div class="face bottom"></div>
</div>
</div>
</body>
<script>
//JavaScript代码
var cube = document.querySelector('.cube');
var container = document.querySelector('#container');
var rotateX = 0, rotateY = 0, rotateZ = 0;
container.addEventListener('mousedown', function(event) {
var startX = event.clientX, startY = event.clientY;
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', mouseMoveHandler);
});
function mouseMoveHandler(event) {
rotateY += event.clientX - startX;
rotateX -= event.clientY - startY;
startX = event.clientX;
startY = event.clientY;
cube.style.transform = 'rotateX(' + rotateX + 'deg) rotateY(' + rotateY + 'deg) rotateZ(' + rotateZ + 'deg)';
}
});
</script>
</html>

以上是3D魔方游戏的HTML和JavaScript代码。该代码实现了一个有动画效果的3D魔方,可以通过鼠标拖动来改变魔方的角度,实现了较好的用户交互体验。