Learn, Share, Build

236
October 02, 2017, at 07:50 AM

I was attempting to place a circle on an HTML canvas that measured 1920 * 850 on (x, y) where x varied by 50 and y varied by 75. I set up a nested for loop to accomplish this but soon found it was not working, i.e. the loop stopped after a certain point. I then did some scenarios with simple nested for loops without the circle placement code and found that they were also stopping after a certain point.

In the code below, I have a simple nested for loop and upon running it, it stops when i = 14 and j = 19. In the console, it just states 'An error has occurred in the Javascript console

for (var i = 0; i < 20; i++) { 
  j = 0 
  for (var j = 0; j < 70; j++) { 
    console.log('i: ' + i + ' j: ' + j); 
  } 
}

Is there something fundamentally wrong here, this seems like such a simple piece of code but I do not know why it would stop.

Any ideas?

Answer 1

I have solved the issue, sort of. I found a post where the console log was not showing the output of a for loop after 999. Additionally, there was an error in my initial javascript loop to produce the circles, I did not use a beginPath after each circle was drawn and that was giving very messed up results.

I.E. Console log with for loop

After reviewing this I realized my code might still be running but the console is not showing it. So I rewrote the code to fill the canvas as I had started out to and it is working now.

$(document).ready(function ()
{
    var header = $('#header');
    var footer = $('#footer');
    var canvas = $('#myCanvas3')[0];
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight - header.height() - footer.height();
    var ctx = canvas.getContext('2d');

    var i = 0;
    var j = 0;
    for (var y = 1; y < 18; y++)
        {
            i = y * 50;
            for (var x = 0; x < canvas.width; x++)
            {
                j += 1;
                if (j == 50) {
                    console.log('x: ' + x);
                    ctx.beginPath();
                    ctx.fillStyle = 'red';
                    ctx.arc(x, i, 2, 0, Math.PI * 2, false);
                    ctx.fill();
                    j = 0;
                }
            }
        }
});

Lesson learned - when drawing items on the canvas make sure to use a beginPath when drawing a new item!!

Rent Charter Buses Company
READ ALSO
Learn, Share, Build

Learn, Share, Build

I have a big main table and I want from there to fill 10 smaller tables to have something like reports (working tables to print)I fill the working tables on different conditions and wrote script for that (thought it's the only way)

227
Learn, Share, Build

Learn, Share, Build

Why won't this work?

242
Learn, Share, Build

Learn, Share, Build

When a user clicks "done" in the iOS default media player I need to direct the page to another url using javascript

226