0

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:\Users\MSI\Documents\ABGG Remastered\StartImg.png"

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

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

    <script src="C:\Users\MSI\Documents\ABGG Remastered\mainScript.js">
    </script>

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

</body>

</html>

Thanks for the help!

SLyCe
  • 33
  • 3
  • Does it work if you try using an image from the internet as opposed to a local file? – The Codesee Aug 13 '21 at 20:23
  • Does this answer your question? [simple HTML5 canvas image not displaying](https://stackoverflow.com/questions/22889641/simple-html5-canvas-image-not-displaying) – The Codesee Aug 14 '21 at 10:12

2 Answers2

2

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:\Users\MSI\Documents\ABGG Remastered\mainScript.js">
    </script>

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

</body>

</html>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
1
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

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

//Images

const BG = new Image();
BG.addEventListener('load', function() {
    ctx.drawImage(BG, 20,20);
})
BG.src = "C:\\Users\\dhrum\\Documents\\Projects\\WizemenDesktop\\WizemenDesktop\\Assets\\icon.png"

</script>

I changed to code to this and it works. First of all, I'd recommend using a method to wait for the image to load, and then draw it (slow servers or large files can take a little to load, and hence wont be drawn if not loaded).

Second of all, your issue that that \ escapes the character, and you'd want to do \\, where the first \ will escape the 2nd \ which would make the actual value of the string with only 1 \.

To understand what escaping a character means, you can go here

Berlm
  • 447
  • 3
  • 7