user3450456 user3450456 - 5 months ago 8
HTML Question

JS function calls won't work

I tried writing a simple JS canvas but it wouldn't draw. If I call the renderCanvas() from the Dev Console in chrome it works, but not if I call it in code. Any ideas why? I'm sure that the picture is there...

<!DOCTYPE html>
<html>
<head>
<title>JSolitaire</title>
</head>
<body>
<canvas id="canvas" width="640" height="480"></canvas>
<script>
renderCanvas();
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var bgReady = false;
var bgImage = new Image();
bgImage.src = "background.png";
bgImage.onload = new function(){
bgReady = true;
};

function renderCanvas(){
if(bgReady)
ctx.drawImage(0, 0, bgImage);
};
</script>
</body>
</html>

Answer

There's no point of using bgReady you can just do this

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");  
var bgImage = new Image();
bgImage.src = "background.png";
bgImage.onload = function() {
    renderCanvas(); 
};  
function renderCanvas() {
    ctx.drawImage(bgImage, 0, 0);
};
Comments