簡體   English   中英

當我使用本地文件時,img src不起作用

[英]img src doesn't work when I use local files

我在畫布上噴雨時遇到了問題。 在谷歌搜索后,我發現了這個

    <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文件,代碼就可以正常工作。 我得到的只是一遍又一遍地繪制文件的副本,直到畫布上充滿線條。

請幫助!

似乎由於某種原因您的背景沒有被渲染。

如果您不希望有任何背景,則必須先清除畫布,然后才能在其新位置繪制水滴,否則您的畫布會泛濫:)

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

另請參見此簡短演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM