Human Cyborg Relations
Human Cyborg Relations

Reputation: 1244

Image not appearing in canvas

I'm trying to load an image on my HTML5 canvas. I'm following a tutorial and I've done everything precisely.

My console prints "image loaded", so I know that it has found the png file. However, nothing shows up on screen.

I have tried resizing the canvas, and trying to make the image appear on different coordinates, to no avail.

<body>
    <canvas id="my_canvas"></canvas>
</body>

<script>
    var canvas = null;
    var context = null;
    var basicImage = null;



    var setup = function() {

        // Set up canvas
        canvas = document.getElementById("my_canvas");
        context = canvas.getContext('2d'); // lets us modify canvas visuals later
        canvas.width = window.innerWidth; // 1200
        canvas.height =  window.innerHeight; // 720

        // Load an image
        basicImage = new Image();
        basicImage.src = "bb8.png";
        basicImage.onload = onImageLoad();
    }

    var onImageLoad = function() {
        console.log("image loaded");
        context.drawImage(basicImage, 0, 0);
    }

    setup();
</script>

Upvotes: 1

Views: 24

Answers (1)

Manav
Manav

Reputation: 1367

Rather than drawing the image on basicImage.onload, try it on window.onload

var setup = function() {

    // Set up canvas
    canvas = document.getElementById("my_canvas");
    context = canvas.getContext('2d'); // lets us modify canvas visuals later
    canvas.width = window.innerWidth; // 1200
    canvas.height =  window.innerHeight; // 720

    // Load an image
    basicImage = new Image();
    basicImage.src = "bb8.png";
}
 window.onload  = function() {
    console.log("image loaded");
    context.drawImage(basicImage, 0, 0);
}

setup();

Upvotes: 1

Related Questions