I've successfully created a spinning cube using html
and css
.
However, I'm facing an issue where pressing the up and down arrow keys causes the cube to rotate in a larger space rather than around its center. I've attempted using margin: 0 auto
, but it only centers the cube on the webpage.
$(document).ready(function(){
var yAngle = 0;
var xAngle = 0;
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '39') {
yAngle = yAngle+5;
$("section").css("transform",'rotateY('+yAngle+'deg)');
}
if (e.keyCode == '37'){
yAngle = yAngle-5;
$("section").css("transform",'rotateY('+yAngle+'deg)');
}
if (e.keyCode == '38'){
xAngle = xAngle+5;
$("section").css("transform","rotateX("+xAngle+"deg)");
}
if (e.keyCode == '40'){
xAngle = xAngle-5;
$("section").css("transform",'rotateX('+xAngle+'deg)');
}
}
$("#button_left").click(function(){
yAngle = yAngle-1;
$("section").css("transform",'rotateY('+yAngle+'deg)');
});
$("#button_right").click(function(){
yAngle = yAngle+1;
$("section").css("transform","rotateY("+yAngle+"deg)");
});
$("#button_down").click(function(){
xAngle = xAngle-1;
$("section").css("transform",'rotateX('+xAngle+'deg)');
});
$("#button_up").click(function(){
xAngle = xAngle+1;
$("section").css("transform","rotateX("+xAngle+"deg)");
});
});
.buttons {
align: center;
}
.wrap {
perspective: 800px;
perspective-origin: 50% 100px;
}
.cube {
margin: 0 auto;
position: relative;
width: 200px;
transform-style: preserve-3d;
}
.cube div {
box-shadow: inset 0 0 20px rgba(125,125,125,0.9);
position: absolute;
width: 200px;
height: 200px;
}
.back {
background: rgba(40,40,40,0.8);
transform: translateZ(-100px) rotateY(180deg);
}
.right {
background: rgba(189,25,400,0.3);
transform: rotateY(-270deg) translateX(100px);
transform-origin: top right;
}
.left {
background: rgba(189,25,400,0.3);
transform: rotateY(270deg) translateX(-100px);
transform-origin: center left;
}
.top {
background: rgba(189,25,400,0.3);
transform: rotateX(-90deg) translateY(-100px);
transform-origin: top center;
}
.bottom {
background: rgba(189,25,400,0.3);
transform: rotateX(90deg) translateY(100px);
transform-origin: bottom center;
}
.front {
background: rgba(189,25,400,0.3);
transform: translateZ(100px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<body><br><br><br><br><br><br>
<div align="center" class="buttons">
<input type="button" value="<--" id="button_left">
<input type="button" value="-->" id="button_right">
<input type="button" value="down" id="button_down">
<input type="button" value="up" id="button_up">
</div>
<br><br><br><br><br><br>
<div class="wrap">
<section class="cube">
<div class="front"></div>
<div class="back"></div>
<div class="top"></div>
<div class="bottom"></div>
<div class="left"></div>
<div class="right"></div>
</section>
</div>