Problems with .drawImage

1

I'm following a tutorial to play the Google T-Rex game but I get the following error in the console: game.js: 45 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D':

  

The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or   HTMLCanvasElement or ImageBitmap or OffscreenCanvas) '       at drawRex (game.js: 45)       at main (game.js: 64)       at juego.js: 57

I was reading line by line but I can not find the error.

document.addEventListener('keydown', function(evento){
	if(evento.keyCode == 32){
		console.log("salta");
	}
});

var imgRex, imgNube, imgCactus, imgSuelo;

function cargaImagenes(){
	imgRex = new Image();
	imgNube = new Image();
	imgCactus = new Image();
	imgSuelo = new Image();

	imgRex.src = "img/rex.png";
	imgNube.src = "img/nube.png";
	imgCactus.src = "img/cactus.png";
	imgSuelo.src = "img/suelo.png";
}




var ancho = 700;
var alto = 300;
var canvas;
var ctx;

function inicializa(){
	canvas = document.getElementById("canvas");
	ctx = canvas.getContext("2d");
}




function borraCanvas(){
	canvas.width = ancho;
	canvas.height = alto;
}

var trex = {y: 250, vy: 0, gravedad: 2, salto: 28, vymax: 9, saltando: false};

function dibujaRex(){
	ctx.drawImage(imgRex,0,0,44,47,100,100,50,50);
}

function gravedad(){

}


//----------------------------------------------------------------------------
//BUCLE PRINCIPAL
var FPS = 10;
setInterval(function(){
	principal();
},1000/FPS);



function principal(){
	borraCanvas();
	dibujaRex();
}
<!DOCTYPE html>
<html>
<head>
	<title>T-Rex</title>
	<script src="juego.js"></script>
</head>
<body onload="inicializa();">
	<canvas id="canvas" width="700" height="300" style="border:2px solid #000000;"></canvas>
</body>
</html>

I do not know if the image will have relevance but I attach it to the doubts:

    
asked by Santiago Arias Gatti 22.12.2017 в 22:00
source

1 answer

0

The cargarImagenes() function is the one that sets the values for imgRex , before that imgRex is only imgRex=undefined , when loads are called to function Principal the one that calls deleteCanvas and drawRex , the latter inside calls drawImage with imgRex as a parameter, but do not call loadImages to set the values of imgRex, define drawRex :

function dibujaRex(){
    cargarImagenes() // para que establezca los valores de imgRex
    ctx.drawImage(imgRex,0,0,44,47,100,100,50,50);
}
    
answered by 22.12.2017 / 22:09
source