Reputation: 1
I was having some difficulties setting up a grid using nested if statements. It's a relatively simple task but I seem to be stuck!
This is a school assignment. The instructions are below:
"If the user enters 8 in the text input and clicks the button, you should draw eight rows and columns of little squares. To do this, you will need two for loops nested inside each other like this:
for ( row=1; ... ) {
for ( col=1; ... ) {
...
}
}
In the (inner-most) loop body, draw a little square on the paper with an x and y value calculated from the loop counters so the squares end up in a grid pattern.
Your page will look something like this (depending on the number the user enters, obviously). Don't worry about the coloured boxes yet: that is the next part."
The outcome should look something like this:
You can ignore the fact that some of squares are colored. So far I'm come up with this:
generate = function() {
n = 0
x = 0
y = 0
n = $('#squares').val()
for (row = 1; row <= n; row += 1) {
for (col = 1; col <= n; col += 1) {
r = paper.rect(x, y, 10,10)
x = x + 20
}
y = y + 20
}
}
setup = function() {
paper = Raphael('container', 400, 400)
$('#number').click(generate)
}
jQuery(document).ready(setup)
Thank you in advance!
Upvotes: 0
Views: 637
Reputation: 815
The starting value for the rows and column in the for loops can be set with the start variable 0
and the condition check row < n
.
Here is an example using javascript and canvas without an external library.
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label>Grid size:</label>
<input type="number" name="go" type="text" name="" id="">
<button class="button">go</button>
<canvas id="canvas" width="400" height="400"></canvas>
</body>
</html>
js:
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
document.getElementsByClassName('button')[0].onclick = function() {
var value = document.querySelector('input[name="go"]').value;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var space = 400 / (value);
for (row = 0; row < value; row += 1) {
for (col = 0; col < value; col += 1) {
ctx.fillRect(row * space, col * space, space - 10, space - 10)
}
}
}
Upvotes: 1