Spirit_Scarlet
Spirit_Scarlet

Reputation: 327

Dynamically adding image source

I have problems regarding printing an image and adding the image source. I have to do it dynamically. I need a random number from 0 to 9 generated and use that number to show that image. I have 10 images

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

The code is this:

<!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>

The last line doesn’t work. If I call that as is

  img.src = “number1.jpg”, 

it shows the image. This way it doesn’t. What can I do to show the image? Thanks

Upvotes: 0

Views: 37

Answers (1)

Dmitry Sadakov
Dmitry Sadakov

Reputation: 2158

You need to populate whichImg right after initializing it:

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

Upvotes: 1

Related Questions