js实现掷骰
实现掷骰子的JavaScript方法
使用Math.random()生成随机数,模拟骰子的6个面(1-6点)。以下是一个基础实现:
function rollDice() {
return Math.floor(Math.random() * 6) + 1;
}
扩展功能:多骰子投掷
通过参数控制骰子数量,返回结果数组:

function rollMultipleDice(count) {
return Array.from({ length: count }, () => rollDice());
}
动画效果增强
结合CSS实现滚动动画效果,提升交互体验:

<div id="dice" class="dice-animation">?</div>
<button onclick="animateRoll()">掷骰子</button>
<script>
function animateRoll() {
const diceElement = document.getElementById('dice');
let rolls = 0;
const animation = setInterval(() => {
diceElement.textContent = rollDice();
if (rolls++ > 10) {
clearInterval(animation);
diceElement.textContent = rollDice(); // 最终结果
}
}, 100);
}
</script>
<style>
.dice-animation {
transition: transform 0.5s;
font-size: 2rem;
}
</style>
概率统计功能
记录历史数据并计算各点数出现概率:
const stats = { 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, total:0 };
function trackRoll(result) {
stats[result]++;
stats.total++;
return (stats[result] / stats.total * 100).toFixed(2) + '%';
}
3D骰子渲染
使用Three.js实现三维骰子(需引入相关库):
const diceGeometry = new THREE.BoxGeometry(1, 1, 1);
const diceMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });
const dice = new THREE.Mesh(diceGeometry, diceMaterial);
function roll3DDice() {
gsap.to(dice.rotation, {
x: Math.PI * (Math.random() * 4),
y: Math.PI * (Math.random() * 4),
duration: 2,
onComplete: () => {
const result = rollDice();
// 根据结果更新骰子纹理
}
});
}






