Skip to content
Advertisement

Canvas Image not showing

I am currently having issues with displaying images in the HTML canvas. I am still new and I am quite tired so its likely theres somthing stupid I did not do. Heres the code:

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

canvas.height = 695;
canvas.width = 1515;

//Images

const BG = new Image();
BG.src = "C:UsersMSIDocumentsABGG RemasteredStartImg.png"

ctx.drawImage(BG, 0, 0);
<!DOCTYPE html>
<html>

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

    <script src="C:UsersMSIDocumentsABGG RemasteredmainScript.js">
    </script>

    <style>
    canvas {
        border: 1px solid;
    }
    </style>

</body>

</html>

Thanks for the help!

Advertisement

Answer

Loading an image is not instantly so you need to wait for it to be loaded first which you can do with the onload function of the image

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

canvas.height = 695;
canvas.width = 1515;

//Images

const BG = new Image();
BG.src = "https://images3.alphacoders.com/899/thumb-1920-899727.jpg"

BG.onload = () => {ctx.drawImage(BG, 0, 0);}
<!DOCTYPE html>
<html>

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

    <script src="C:UsersMSIDocumentsABGG RemasteredmainScript.js">
    </script>

    <style>
    canvas {
        border: 1px solid;
    }
    </style>

</body>

</html>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement