开发者

How to loop a drawLine so it repeats itself 10 times

I am currently trying to create a sudoku grid in javascript, to do this I need to set up a loop so one l开发者_如何学JAVAine re-appears 10 times with a gap of 20 pixels between each one. So far I have:

var canvas;
canvas = openGraphics();

var x;
var y;
var gap;
x = 20;
y = 20;
gap = 25;

canvas.drawLine(20, 20, 20, 245);

canvas.paint();

How would you recommend to do this?


As you already stated, you have to use a looping construct.

The Mozilla Developer Network has good documentation on these.

But honestly, I think you should rather read their JavaScript Guide before trying to write a Game, otherwise you'll end up bumping into a ton of dead ends and you will soon loose the interest in making the game at all.

Also, please stay on MDN when searching looking JavaScript help, since there are a lot of sites on the Internet that have bad, old, broken code example and help.

Especially stay away from w3schools.


There are various looping constructs available to programmers, the 2 most common ones are the for loop and the while loop.

The for loop is good for "looping" a number of times and the while loop is for looping while some value is "true".

In this case, you know the number of lines that you need to draw so the for loop is best matched

This is example code for the for loop. What happens is that the code between the { and } is run multiple time. Each time the loop runs, variable i gets larger by 1, starting from 0. This continues until the condition i<numberTimesToLoop becomes false.

for(var i=0;i<numberTimesToLoop;i++)
{
    document.write("i = " + i);
    document.write("<br />");
}

Not that I want to do your assignment for you, but in a lot of cases its easier to learn from seeing actual code. (I demonstrate and I find plenty of students who on seeing an answer can immediately recognise it in the future. Of course I give them the theory first and if it doesn't click I try this method...)

This modification to your current code will draw your vertical lines.

var canvas;
canvas = openGraphics();

var x;
var y;
var gap;
x = 20;
y = 20;
gap = 25;


var currentX = 20;
for(var i=0;i<10;i++)
{
    canvas.drawLine(currentX, 20, currentX, 245);
    currentX = currentX + gap;
}
canvas.paint();

(Not really sure what the problem with the w3schools website is)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜