首次调用该函数时,以下代码有效。但是,当我再次调用setup()函数时,速度增加了(图像下降得更快)。我试图弄清楚如何在不每次调用函数时都提高速度的情况下保持初始速度。我已经为此工作了好几天。任何帮助将不胜感激。
(为什么需要这样做:我正在开发一项功能,该功能允许用户在4种不同类型的下降图像之间切换。用户将单击图像,这将触发该功能。但是,每次用户单击下降时,速度增加。)
<canvas id="canvasRegn" width="1000" height="450"style="margin:100px;position:relative;z-index:999999;opacity:0.2;">
var ctx;
var imgBg;
var imgDrops;
var x = 0;
var y = 0;
var noOfDrops = 50;
var fallingDrops = [];
function drawBackground(){
ctx.drawImage(imgBg, 0, 0); //Background
}
function draw() {
drawBackground();
for (var i=0; i< noOfDrops; i++)
{
ctx.drawImage (fallingDrops[i].image, fallingDrops[i].x, fallingDrops[i].y); //The rain drop
fallingDrops[i].y += fallingDrops[i].speed; //Set the falling speed
if (fallingDrops[i].y > 450) { //Repeat the raindrop when it falls out of view
fallingDrops[i].y = -25 //Account for the image size
fallingDrops[i].x = Math.random() * 1000; //Make it appear randomly along the width
}
}
}
function setup() {
var canvas = document.getElementById('canvasRegn');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
imgBg = new Image();
imgBg.src = "/BACKGROUND.png";
setInterval(draw, 36);
for (var i = 0; i < noOfDrops; i++) {
var fallingDr = new Object();
fallingDr["image"] = new Image();
fallingDr.image.src = '/image.png';
fallingDr["x"] = Math.random() * 1000;
fallingDr["y"] = Math.random() * 5;
fallingDr["speed"] = 3 + Math.random() * 5;
fallingDrops.push(fallingDr);
}
}
}
setup();
最佳答案
您没有取消前一个setInterval
。在第二个setup
调用之后,您正在每单位时间执行draw
两次,依此类推。
...
var fallingDrops = [];
var timer = null;
...
clearInterval(timer);
timer = setInterval(draw, 36);
...
关于javascript - Javascript中的图片下降(图片下降太快),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44730707/