I'm creating a Canvas game, the code below shows the global variables and the init function. From my understanding creating global variables is bad practice and may lead to clashes with other files.
Can someone give me an example of how to improve this code using IIFE?
canvasEntities = document.getElementById("canvasEntities"), // foreground canvas
ctxEntities = canvasEntities.getContext("2d"),
canvasWidth = 400,
canvasHeight = 400,
player1 = new Player(),
enemies = [],
numEnemies = 5,
obstacles = [],
isPlaying = false,
requestAnimFrame = window.requestAnimationFrame || // Controls timing and update of game
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) { // Older broswers
window.setTimeout(callback, 1000 / 60);
},
imgSprite = new Image(); // create sprite object
imgSprite.src = "images/sprite.png";
imgSprite.addEventListener("load", init, false);
// event listener looks at image sprite waits for it to load, then calls init
function init() {
defineObstacles();
initEnemies();
begin();
}