先利用css和html写出一个简易的骰子
先确定骰子的六个面
<div id="box">
<div class="box1">1</div>
<div class="box2">2</div>
<div class="box3">3</div>
<div class="box4">4</div>
<div class="box5">5</div>
<div class="box6">6</div>
</div>
再加上点css
#box {
width: 100px;
height: 100px;
margin: 400px 400px;
position: relative;
background-color: red;
transform: rotate3d(0, 0, 0, 30deg);
transform-style: preserve-3d;
transition: all 0.5s;
}
#box div {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
font-size: 100px;
text-align: center;
line-height: 100px;
}
.box1 {
background-color: aqua;
transform: rotateX(-90deg);
transform-origin: bottom center;
}
.box2 {
background-color: red;
transform: rotateX(90deg);
transform-origin: top center;
}
.box3 {
background-color: green;
transform: rotateY(-90deg);
transform-origin: left center;
}
.box4 {
background-color: yellowgreen;
transform: rotateY(90deg);
transform-origin: right center;
}
.box5 {
background-color: antiquewhite;
transform: rotateY(180deg);
z-index: 10;
}
.box6 {
background-color: rgb(130, 114, 250);
transform: translateZ(100px);
}
上面完成后就是一个简易的骰子的样子,因为扔骰子是随机的,所以加上随机数和点击事件
让box的旋转角度为90的倍数,可以单面向上,下面为js的代码
window.onload = function () {
var oDiv = document.getElementById('box');
var min = 10;
var max = 20;
// parseInt(Math.random() * (max - min + 1) + min, 10);
document.body.onclick = function () {
var a = Math.floor(Math.random() * (max - min + 1) + min);
var b = Math.floor(Math.random() * (max - min + 1) + min);
oDiv.style.transform = 'rotateX(' + a * 90 + 'deg) rotateY(' + b * 90 + 'deg)';
}
}
这样一个简易的骰子就做好了