Reputation: 932
I am currently working on writing small game that is written in javascript, alot like "snake". Part of it is that me showing grid and that grid needs to be updated often.
And one way for me to do that is using below function.
function loadImages(){
for(var i = 0;i<HEIGHT;i++){
for(var j = 0;j<WIDTH;j++){
if(grid[i][j] == -1){
document.write('<IMG SRC="wall.png" width="30">');
}
else if(grid[i][j] == 0){
document.write('<IMG SRC="empty.png" width="30">');
}
}
}
setTimeout( loadImages(), 50 );
}
Only problem is that when loadImages() function is called over and over, images are concatenated not, replacing.
So my questions is that is there a way to overwrite document, or clear?
P.S. "document.clear()" function doesn't seems to be all that helpful.
Thank you
Upvotes: 0
Views: 3274
Reputation: 655239
You could extend your grid
data structure and store both the state and the image element:
// initialization
for(var i = 0;i<HEIGHT;i++) {
for(var j = 0;j<WIDTH;j++){
grid[i][j] = {
state: grid[i][j],
image: new Image() // creates HTMLImageElement object
};
// set width
grid[i][j].image.setAttribute("width", "30");
// append HTMLImageElement to BODY element
document.body.appendChild(grid[i][j].image);
}
}
Then you can change the images inside loadImages
in a similar manner:
function loadImages() {
for(var i = 0;i<HEIGHT;i++){
for(var j = 0;j<WIDTH;j++){
if(grid[i][j].state == -1){
grid[i][j].image.src = "wall.png";
}
else if(grid[i][j].state == 0){
grid[i][j].image.src = "empty.png";
}
}
}
setTimeout(loadImages, 50);
}
By the way: setTimeout(loadImages(), 50)
calls loadImages
immediately but you should pass the function instead, so setTimeout(loadImages, 50)
.
You can optimize this your loadImages
function by storing grid[i][j]
in a temporary variable and only change the images’ source if the state has changed:
var cell = grid[i][j];
switch (cell.state) {
case -1:
if (cell.image.src !== "wall.png") {
cell.image.src = "wall.png";
}
break;
case 0:
if (cell.image.src !== "empty.png") {
cell.image.src = "empty.png";
}
break;
}
Upvotes: 2
Reputation: 6640
The simplest thing would be to not use document.write
, but to instead write to a particular document element. For example, start with the following document:
<html>
<head>...</head>
<body><div id='game'></div></body>
</html>
Then instead of "document.write", do:
var game = document.getElementById('game');
game.innerHTML = '<IMG SRC="wall.png" width="30">';
You could set the game.innerHTML property frequently, and it will overwrite.
Upvotes: 2
Reputation: 49208
document.write is always additive; you're always adding a new element(s) to the document object (DOM).
What you want, in this case, is document.getElementById('imgParent').innerHTML, with the child(ren) image(s) being within the element with ID.
document.getElementById('imgParent').innerHTML = '<IMG SRC="wall.png" width="30">';
Really, though, consider a library like jQuery:
Upvotes: 2