Random images falling like rain in canvas (Javascript)

后端 未结 1 647
星月不相逢
星月不相逢 2020-12-18 11:08

So I have been playing around with canvas. Trying to simulate random falling objects, drawing the background image is no problem and not the 2nd img that is supposed to simu

相关标签:
1条回答
  • 2020-12-18 11:59

    Your loop is actually pretty close. The biggest problem you would have is that you can't just maintain 1 x and 1 y value, you have to maintain that per image. So I modified your loop a bit to push an object on the array that has an x,y, and speed value. The speed value gives you nice randomization of the movement, so everything doesn't come down at the same speed:

    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() * 600;    //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 = "http://lorempixel.com/600/600/sports/";
            setInterval(draw, 36);
            for (var i = 0; i < noOfDrops; i++) {
                var fallingDr = new Object();
                fallingDr["image"] =  new Image();
            fallingDr.image.src = 'http://lorempixel.com/10/10/sports/';
    
                fallingDr["x"] = Math.random() * 600;
                fallingDr["y"] = Math.random() * 5;
                fallingDr["speed"] = 3 + Math.random() * 5;
                fallingDrops.push(fallingDr);
                }
    
            }
        }
    
    setup();
    

    Here is a fiddle demo: http://jsfiddle.net/L4Qfb/21/

    0 讨论(0)
提交回复
热议问题