我正在尝试创建一个diceroll,一个表示多个数字然后才能结算为一个。我尝试了一个非常简单的方法,但它不起作用:这是我的代码:
<script>
//preload the six images first
var face0=new Image()
face0.src="http://www.unisg.bplaced.net/dices/d1.gif"
var face1=new Image()
face1.src="http://www.unisg.bplaced.net/dices/d2.gif"
var face2=new Image()
face2.src="http://www.unisg.bplaced.net/dices/d3.gif"
var face3=new Image()
face3.src="http://www.unisg.bplaced.net/dices/d4.gif"
var face4=new Image()
face4.src="http://www.unisg.bplaced.net/dices/d5.gif"
var face5=new Image()
face5.src="http://www.unisg.bplaced.net/dices/d6.gif"
function delay(time) {
var d1 = new Date();
var d2 = new Date();
while (d2.valueOf() < d1.valueOf() + time) {
d2 = new Date();
}
}
</script>
<img src="http://www.unisg.bplaced.net/dices/d1.gif" name="mydice">
<form><br><br>
<input type="button" value="Throw dice!" onClick="throwdice(); throwdices();">
</form>
<script type="text/javascript">
function DoAllThese() {
throwdice();
throwdices();
}
function throwdice(){
delay(500);
document.images["mydice"].src=eval("face"+5+".src");
delay(500);
throwdices();
}
function throwdices(){
var randomdices=Math.round(Math.random()*4.5);
delay(1000);
document.images["mydice"].src=eval("face"+randomdices+".src");
}
</script>
我不确定如何对这些数字进行排序,使其看起来像骰子在进入解决方案之前会旋转。
答案 0 :(得分:1)
使用setInterval
:
function throwdices() {
var spins = 10;
var curSpin = 0;
var spinInterval = setInterval(function() {
curSpin++;
if (curSpin < spins) {
var randomdices=Math.round(Math.random()*4.5);
document.images["mydice"].src=eval("face"+randomdices+".src");
} else {
clearInterval(spinInterval);
throwdice();
}
}, 500);
}