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 8042181
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T04:29:31+00:00 2026-06-05T04:29:31+00:00

var c=document.getElementById(cvs); var ctx=c.getContext(2d); var imgArray = []; for (var i=0;i<data.length;i++){ var drawRepeat =

  • 0
var c=document.getElementById("cvs");
var ctx=c.getContext("2d");
var imgArray = [];          
for (var i=0;i<data.length;i++){
    var drawRepeat = Math.floor((data[i]/divider)); 
    imgArray[i] = [];   
    for (var j=0;j<drawRepeat;j++){
            //alert(j);
        var xPos = ((i*30)+10);
        var yPos = 250-((j*30)+30);
        imgArray[i][j] = new Image();
        imgArray[i][j].src="assets/orange.png";
        imgArray[i][j].onload = function(){
        ctx.drawImage(imgArray[i][j],xPos,yPos);
        };

    }
}

I want to draw multiple images with a for loop. weirdly when i place an alert() with the for loop it works? but if i comment it away it will only display 1 of the image.

Is there any solution to this?

  • 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-05T04:29:34+00:00Added an answer on June 5, 2026 at 4:29 am

    That’s the problem related to closures. I’ll explain after giving the code.

    var c = document.getElementById("cvs");
    var ctx = c.getContext("2d");
    var imgArray = [];
    for (var i = 0; i < data.length; i++) {
        var drawRepeat = Math.floor((data[i] / divider));
        imgArray[i] = [];
        for (var j = 0; j < drawRepeat; j++) {
            //alert(j);
            (function (_i, _j) {
                var xPos = ((_i * 30) + 10);
                var yPos = 250 - ((_j * 30) + 30);
                imgArray[_i][_j] = new Image();
                imgArray[_i][_j].src = "assets/orange.png";
                imgArray[_i][_j].onload = function () {
                    ctx.drawImage(imgArray[_i][_j], xPos, yPos);
                };
            })(i, j);
        }
    }
    

    UPDATE:

    The reason I am doing this weird stuff is that the function registered to onload event will be called asynchronously – that is the loop will continue and the function will be called when the image loads, and not at that very moment. So what happens is that this loop continues, and once it’s completed (note that this may occur even before completion), i‘s value will be data.length - 1. Now, some image is loaded, and then the function is called. This function refers to i (in the code you gave), which by now is data.length - 1. And so, only the last image gets drawn. I know this is confusing – even I felt it confusing when I first stumbled upon closures. I recommend you read some good article on them and you’ll see what the problem is.

    What we did was to create a scope (experts might find a problem with this expression) by creating an anonymous function which is called immediately, and is passed the values of i and j as it’s parameters – _i and _j (Note that we could’ve used the same names, but to avoid confusion, I didn’t use the same names). Now, these are local to the function and aren’t altered. So, when ith image is loaded, it’s onload function is called which draws the _ith image in the array.

    I have failed to explain it well, so as I said, please read some article on closures.

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

Sidebar

Related Questions

$(function() { var number = document.getElementById(breuken); var i=0; for (i=1;i<=10;i++){ var fRandom = Math.floor(Math.random()*10);
function showContent(tableID) { var tbl = document.getElementById(tableID); var rCount = tbl.rows.length; try { alert(tbl.rows[rCount
I have the following code var email = document.getElementById(email).value; $.post(/valid,{emailadd: email},function(data){ alert(data); }); on
For example if I assign var n = document.getElementById('A').childNodes.length; And then later append a
This works : alert(document.getElementById(Container).nodeName); But this doesnt : var CurParent = document.getElementById(Container); alert(CurParent.nodeName); I
I used the following function: function datediff() { var dat1 = document.getElementById('date1').value; alert(dat1);//i get
Actually my code is--- function addElement(url,imagePath){ alert(url); alert(imagePath); var container = document.getElementById('sncs'); var new_element
var tbl = document.getElementById(TABLE_NAME); var nextRow = tbl.tBodies[0].rows.length; row.setAttribute('style', cursor: pointer;); This will add
var x = document.getElementById(testingAjax); if (x != null) { var left = x.position().left; alert(left);
var table = document.getElementById(table1); var lastRow = table.rows.length; var country = lastRow.getElementById('Country'); country.setAttribute('class', Country+lastRow);

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.