I am not able to draw only one HUD of my game on a separate canvas, so I do not have to redraw it to each frame, I have four functions, init(), render(), loop() and drawHUD():
init() is my function that I call when starting the game, right at the end of the script.
render() is my rendering function
loop() is my game loop function (do not notice it, I've simplified it with minimal to leave the code cleaner for reading)
drawHUD() is my function to draw HUD on Canvas HUD_CANVAS
The problem is that the code below does not work, the screen remains blank, but if I put drawHUD() inside the render() before CTX.drawImage (HUD_CANVAS, 0, 0);
then it works and I can see the image on the screen, however I wish I could draw only once, not every frame, since my HUD will not always be updating.
What am I doing wrong?
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Test</title>
<style type="text/css" media="screen">
canvas {
padding: 0;
margin: auto;
display: block;
width: 640px;
height: 480px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
border: 1px solid #999;
}
</style>
</head>
<body>
<canvas id="canvas" style="z-index: 0;" width="640" height="480"></canvas>
<canvas id="hud-canvas" style="z-index: 1;" width="640" height="480"></canvas>
<script>
const CANVAS = document.getElementById('canvas');
const CTX = CANVAS.getContext('2d');
const HUD_CANVAS = document.getElementById('hud-canvas');
const HUD_CTX = HUD_CANVAS.getContext('2d');
function drawHUD() {
const imgHUD = new Image();
imgHUD.src = './hand_hud_maya.png';
HUD_CTX.drawImage(imgHUD, 0, 0, 96, 96, 0, 0, 96, 96);
}
function init() {
drawHUD();
loop();
}
function render() {
CTX.drawImage(HUD_CANVAS, 0, 0);
}
function loop() {
render();
requestAnimationFrame(loop);
}
init();
</script>
</body>
</html>
Example:
https://jsfiddle.net/twkq0sn6/
Up1:
Change that part of the function, I can see the red rectangle on the screen, so I think the problem is with the drawImage() function, but I do not know what it can be, I already tested several images, I do not think it's the image.
function drawHUD() {
HUD_CTX.fillStyle = "red";
HUD_CTX.fillRect(50, 50, 50, 50);
}
the image is loaded properly, I can see in the chrome network tab the preview of it, all OK. I do not get any errors, it's hard to figure out where I'm going wrong.