Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7844873
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T17:02:16+00:00 2026-06-02T17:02:16+00:00

I’m trying to draw a grid with random images assigned to each square. I’m

  • 0

I’m trying to draw a grid with random images assigned to each square. I’m having trouble with the draw sequence and potentially closure issues with the Javascript variables. Any help is appreciated.

var tileSize = 30;
var drawCanvasImage = function(ctx,tile,x,y) {
return function() {
    ctx.drawImage(tile,x,y);
    console.log("x = " + x + "/ y = " + y);
}
}

function textures(ctx) {
var grass = new Image();
var sea = new Image();
var woods = new Image();
for (var i=0; i<=10; i++) {
    for (var j=0; j<=20; j++) {
        rand = Math.floor(Math.random()*3 + 1);
        x = i * tileSize;
        y = j * tileSize;
        if (rand == 1) {
            grass.onload = drawCanvasImage(ctx,grass,x,y);
        } else if (rand == 2) {
            sea.onload = drawCanvasImage(ctx,sea,x,y);
        } else {
            woods.onload = drawCanvasImage(ctx,woods,x,y);
        }
    }
}
grass.src = "textures/grass.png";
sea.src = "textures/sea.png";
woods.src = "textures/woods.png";
}

//function called by the onload event in the html body tag
function draw() {
var ctx = document.getElementById("grid").getContext('2d');
grid(ctx);  //a function to draw the background grid - works fine
textures(ctx);
}

The current result is three drawn tiles, all at the position of x = 300 (equivalent to the i loop of 10 * the tileSize of 30) and a random y position.

After following a lead and accounting for (maybe?) closure issues by creating the variable drawCanvasImage, I at least got those three tiles to draw.

—-Edit—-
Working Code – Revision 2:

function randomArray() {
for (var i=0; i<=(xValue/tileSize); i++) {
    terrainArray[i] = [];
    for (var j=0; j<=(yValue/tileSize); j++) {
        rand = Math.floor(Math.random()*4 + 1);
        if (rand == 1) {
            terrainArray[i][j] = 3;
        } else if (rand == 2) {
            terrainArray[i][j] = 2;
        } else if (rand == 3) {
            terrainArray[i][j] = 1;
        } else {
            terrainArray[i][j] = 0;
        }
    }
}
}

var drawTerrain = function(ctx,tile,landUseValue) {
return function() {
    for (var i=0; i<=(xValue/tileSize); i++) {
        for (var j=0; j<=(yValue/tileSize); j++) {
            if (terrainArray[i][j] == landUseValue) {
                ctx.drawImage(tile,i*tileSize,j*tileSize);
            }
        }
    }
}
}

function textures(ctx) {
var grass = new Image();
var sea = new Image();
var woods = new Image();
var desert = new Image();
grass.onload = drawTerrain(ctx,grass,3);
sea.onload = drawTerrain(ctx,sea,0);
woods.onload = drawTerrain(ctx,woods,2);
desert.onload = drawTerrain(ctx,desert,1);
grass.src = "textures/grass.png";
sea.src = "textures/sea.png";
woods.src = "textures/woods.png";
desert.src = "textures/desert.png";
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T17:02:17+00:00Added an answer on June 2, 2026 at 5:02 pm

    You’re rewriting the onloads of the three images in every iteratiom. So, it will only execute the last-added onload f or every image.

    Suggestion: run your drawing method only after the thred are loaded(and them just call drawCanvasImage every iteration without an .onload=)

    Even better:store the randoms in an array, have each image independantly walk through the array on load and add copies of only itself wherever applicable .

    Improvement to rev 2

    function randomArray() {
    for (var i=0; i<=(xValue/tileSize); i++) {
        terrainArray[i] = [];
        for (var j=0; j<=(yValue/tileSize); j++) {
            rand = Math.floor(Math.random()*4 + 1);
            terrainArray[i][j] = 4-rand; 
            //OR: replace above two lines with terrainArray[i][j]=Math.floor(Math.random()*4 + 1);. There's no need to have them in exactly reverse order.
        }
    }
    }
    
    var drawTerrain = function(ctx,tile,landUseValue) {
    return function() {
        for (var i=0; i<=(xValue/tileSize); i++) {
            for (var j=0; j<=(yValue/tileSize); j++) {
                if (terrainArray[i][j] == landUseValue) {
                    ctx.drawImage(tile,i*tileSize,j*tileSize);
                }
            }
        }
    }
    }
    
    function textures(ctx) {
    var grass = new Image();
    var sea = new Image();
    var woods = new Image();
    var desert = new Image();
    grass.onload = drawTerrain(ctx,grass,3);
    sea.onload = drawTerrain(ctx,sea,0);
    woods.onload = drawTerrain(ctx,woods,2);
    desert.onload = drawTerrain(ctx,desert,1);
    grass.src = "textures/grass.png";
    sea.src = "textures/sea.png";
    woods.src = "textures/woods.png";
    desert.src = "textures/desert.png";
    }
    

    To make it even more flexible, you could use an array to store the images, and then use length. This way, if you want to add another image, all you have to do is modify the array.

    var srcArray=["textures/grass.png","textures/sea.png","textures/woods.png","textures/desert.png"];
    var imgArray=[];
    var terrainArray=[];
    function textures(ctx){
    randomArray();
        for(var i=0;i<srcArray.length;i++){
            imgArray[i]=new Image();
            imgArray[i].src=srcArray[i];
            imgArray[i].onload=drawTerrain(ctx,i);
        }
    }
    function randomArray() {
    for (var i=0; i<=(xValue/tileSize); i++) {
        terrainArray[i] = [];
        for (var j=0; j<=(yValue/tileSize); j++) {
            terrainArray[i][j]=Math.floor(Math.random()*srcArray.length);
    
        }
    }
    }
    
    var drawTerrain = function(ctx,index) {
    return function() {
        for (var i=0; i<=(xValue/tileSize); i++) {
            for (var j=0; j<=(yValue/tileSize); j++) {
                if (terrainArray[i][j] == index) {
                    ctx.drawImage(imgArray[index],i*tileSize,j*tileSize);
                }
            }
        }
    }
    }
    

    So now, all you have to do is call terrain(ctx) when you want to load all the images. And, whenever you want to add an image to the list of images, just add it to the array up top. You won’t have to dig deeper and modify the random values and whatnot.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
Basically, what I'm trying to create is a page of div tags, each has
I am trying to understand how to use SyndicationItem to display feed which is
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.