动态添加图像源

时间:2015-04-23 22:12:56

标签: javascript html canvas

我在打印图像和添加图像源时遇到问题。我必须动态地做。我需要一个从0到9的随机数生成并使用该数字来显示该图像。我有10张图片

 (number0.jpg, number1.jpg, number2.jpg…). 

代码是这样的:

<!DOCTYPE html>
<html> 
<body>
<canvas id="canvas" width="258" height="187"></canvas>
<script>
var can = document.getElementById('canvas');
            var ctx = can.getContext('2d');
    var whichImg;
    var randNum;

    var img = new Image();
    img.onload = function(){
    randNum = Math.floor(Math.random() * 10);
    can.width = img.width;
    can.height = img.height;
    whichImg="number" + randNum + ".jpg" ;
    ctx.drawImage(img, 0, 0, img.width, img.height);

    }
    img.src = whichImg; //having problems with this row

    </script>
     </body>
    </html>

最后一行不起作用。如果我按原样称呼

  img.src = “number1.jpg”, 

显示图像。这种方式没有。我该怎么做才能显示图像? 感谢

1 个答案:

答案 0 :(得分:1)

您需要在初始化后立即填充whichImg

var can = document.getElementById('canvas');
        var ctx = can.getContext('2d');
var whichImg;
var randNum;
randNum = Math.floor(Math.random() * 10);
whichImg="number" + randNum + ".jpg" ;

var img = new Image();
img.onload = function(){
randNum = Math.floor(Math.random() * 10);
can.width = img.width;
can.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);

}
img.src = whichImg; //having problems with this row