js实现色子
实现色子的基本思路
使用JavaScript创建一个色子(骰子)模拟器,可以通过随机数生成1到6的数字,并显示对应的骰子点数图形。
HTML结构
创建一个简单的HTML容器,用于显示骰子图形和结果:
<div id="dice-container">
<div id="dice-face"></div>
<button id="roll-btn">掷骰子</button>
<p id="result"></p>
</div>
CSS样式
为骰子添加基本样式,使其显示为正方形并包含点数:
#dice-face {
width: 100px;
height: 100px;
background-color: white;
border: 2px solid black;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
font-size: 50px;
margin: 20px;
}
JavaScript实现
使用DOM操作和随机数生成骰子结果:
const rollBtn = document.getElementById('roll-btn');
const diceFace = document.getElementById('dice-face');
const resultText = document.getElementById('result');
rollBtn.addEventListener('click', () => {
// 生成1-6的随机数
const randomNum = Math.floor(Math.random() * 6) + 1;
// 更新骰子图形
diceFace.textContent = getDiceFace(randomNum);
// 显示结果
resultText.textContent = `你掷出了: ${randomNum}`;
});
// 返回对应数字的骰子图形
function getDiceFace(num) {
const diceFaces = {
1: '⚀',
2: '⚁',
3: '⚂',
4: '⚃',
5: '⚄',
6: '⚅'
};
return diceFaces[num];
}
进阶实现:动画效果
添加掷骰子的动画效果,使体验更真实:
rollBtn.addEventListener('click', () => {
// 禁用按钮防止重复点击
rollBtn.disabled = true;
// 动画效果
let rolls = 0;
const animationInterval = setInterval(() => {
const tempNum = Math.floor(Math.random() * 6) + 1;
diceFace.textContent = getDiceFace(tempNum);
rolls++;
if(rolls > 10) {
clearInterval(animationInterval);
const finalNum = Math.floor(Math.random() * 6) + 1;
diceFace.textContent = getDiceFace(finalNum);
resultText.textContent = `你掷出了: ${finalNum}`;
rollBtn.disabled = false;
}
}, 100);
});
使用Canvas绘制骰子
如需更自定义的骰子图形,可以使用Canvas API:
function drawDiceFace(num) {
const canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 100;
const ctx = canvas.getContext('2d');
// 绘制骰子背景
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, 100, 100);
ctx.strokeStyle = 'black';
ctx.strokeRect(0, 0, 100, 100);
// 根据数字绘制点数
ctx.fillStyle = 'black';
const positions = {
1: [[50, 50]],
2: [[20, 20], [80, 80]],
3: [[20, 20], [50, 50], [80, 80]],
4: [[20, 20], [20, 80], [80, 20], [80, 80]],
5: [[20, 20], [20, 80], [50, 50], [80, 20], [80, 80]],
6: [[20, 20], [20, 50], [20, 80], [80, 20], [80, 50], [80, 80]]
};
positions[num].forEach(pos => {
ctx.beginPath();
ctx.arc(pos[0], pos[1], 8, 0, Math.PI * 2);
ctx.fill();
});
return canvas;
}






