0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I've been trying to solve this for a long time, so thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.