当我使用本地文件时,img src不起作用

时间:2013-05-18 14:42:17

标签: javascript loops animation canvas

我在画布上遇到雨水问题。经过谷歌搜索后我发现了这个

    <script type="text/javascript">
var ctx;
var imgBg;
var imgDrops;
var x = 0;
var y = 0;
var noOfDrops = 50;
var fallingDrops = [];

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);
        }

    }
}

   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 drawBackground(){  
    ctx.drawImage(imgBg, 0, 0); //Background
}

    </script>

奇怪的是,只要我不将图像源从链接更改为我的png文件,代码就可以工作。我得到的是我的文件的副本一遍又一遍地绘制,直到画布的线条充满。

请帮忙!

1 个答案:

答案 0 :(得分:0)

似乎由于某种原因你的背景没有渲染。

如果你不想拥有任何背景,你必须先清除画布,然后再画下新的位置,否则你的画布会泛滥:)

替换:ctx.drawImage(imgBg, 0, 0);
用:clearRect(0, 0, width, height)

另请参阅此 short demo