Javascript中的图像下降(图像下降太快)

时间:2017-06-23 22:24:06

标签: javascript jquery image

以下代码在首次调用该函数时有效。但是,当我再次调用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();

2 个答案:

答案 0 :(得分:1)

您没有取消之前的setInterval。在第二次setup通话后,您每个单位时间执行draw两次,依此类推。

...
var fallingDrops = [];
var timer = null;

...

clearInterval(timer);
timer = setInterval(draw, 36);

...

答案 1 :(得分:0)

setInterval调用可能相互堆叠,导致drawBackground比你想象的更频繁地发生。

创建一个变量来保存您的&#39; setInterval&#39;:

var drawRepeater = setInterval(draw, 36);

在重新调用setInterval:

之前添加clearInterval
clearInterval(drawRepeater);
var drawRepeater = setInterval(draw, 36);