Reputation: 33
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!
Upvotes: 0
Views: 722
Reputation: 467
<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
Upvotes: 1
Reputation: 31351
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>
Upvotes: 2