我有这个功能
var flakeImage = new Image();
function loadImage(){
flakeImage.onload = drawFlake;
flakeImage.src = "game/snowflake.png";
}这是初始化图像的方法
function initFlake() {
flakex = Math.random()*(WIDTH-140)+70;
flakey = (Math.random()*20)+70;
flakes = Math.random()*40;
}这个更新了图像,这样它看起来就像是真的在下落。
function updateFlake(){
flakey = flakey + 1;
}还有draw函数
function drawFlake() {
context.drawImage(flakeImage, flakex, flakey, flakes, flakes);
}我想让它看起来像是在我的画布上下雪。我不能使用for循环,因为它只会修改相同的图片。我试着用同样的图片做一个大的数组,但最后我没有得到那个效果。因为图像必须一直随机地下落。我应该如何将一个数组与存储在随机位置上有一定间隔的图像组合在一起才能得到这样的效果呢?
发布于 2014-12-03 02:36:34
您可以使用setInterval()。
doSomething: function() {
clearInterval(myInterval);
myInterval = setInterval(function() {
// update flake position
updateFlake();
}, timeInMilliseconds);
},这将每隔timeInMilliseconds毫秒运行一次作为参数提供的函数。setInterval()函数返回一个ID,您可以将其传递给clearInterval()以停止更新。
您也可以直接传递函数。
doSomething: function() {
clearInterval(myInterval);
myInterval = setInterval(updateFlake, timeInMilliseconds);
},EDIT: OP,您可以在不依赖HTML5画布的情况下很好地做到这一点,而使用DOM元素:
Javascript:
function update () {
var myInterval = null;
clearInterval(myInterval);
myInterval = setInterval(function() {
// update flake position
$("#holder > img").each(function() {
if ($(this).position().top >= $(window).height())
$(this).remove();
else
$(this).css({top: $(this).position().top+=3});
});
}, 50); //update each of the drawn children
}
function drawFlake() {
clearInterval(myInterval);
var myInterval = null;
myInterval = setInterval(function() {
var randX = (Math.floor((Math.random() * $(window).width()) + 1));
var $img = $('<img>');
$img.attr('src','flake.png');
$("#holder").append($img);
$img.css({left: randX, top: 0, position:'absolute'});
}, 2000); //draw a new flake every 2 seconds
update();
}HTML:
<body onload="drawFlake()">
<div id="holder"></div>
</body>CSS:
body {
background: white;
}
#holder {
position: relative;
width: 100%;
height: 100%;
}https://stackoverflow.com/questions/27256486
复制相似问题