Why javascript does not draw images on canvas?

I have a problem with drawing images on my canvas. No errors, but no images. Look at the code snippet and see if you can see that I cannot:

function loadPacman(posX, posY) { this.posX = posX; this.posY = posY; pacman = new Image(); pacman.src="http://www.frogbug.se/pacman/img/naziman.png"; pacman.addEventListener("load", function(){ canvas.drawImage(pacman, this.posX, this.posY) }, false); } function loadGhost(posX, posY) { this.posX = posX; this.posY = posY; ghost = new Image(); ghost.src="http://www.frogbug.se/pacman/img/ghost.png"; ghost.addEventListener("load", function(){ canvas.drawImage(ghost, this.posX, this.posY) }, false); } 

And this is my function that loads when the page loads:

 function onLoad() { var xy = document.getElementById('canvas'); canvas = xy.getContext('2d'); //calculate the x and y for canvas x = xy.width; y = xy.height; //divide the width and length of the canvas to get small cubes //which is 40x40 xtile = Math.floor(x/40); ytile = Math.floor(y/40); //draw lines around the canvas canvas.strokeRect(0, 0, x, y); //the array for the map var map = getMapArray(); //draw the map drawMap(map); //fillCanvas("0010", 0, 40, 40, 40); //load the ghost and pacman loadPacman(0, 0); loadGhost((xtile*40)-40, (ytile*40)-40); } 

Thanks in advance! You can view the full source and so on: http://www.picturds.com/pacman_serious/

+4
source share
1 answer

Remove this from this.posX and this.posY in the load callback. this in this context is the image element, and not the same this as when assigning this.posX (which is equal to window ).

http://jsfiddle.net/5dkx4/

+4
source

Source: https://habr.com/ru/post/1390578/


All Articles