Cycles while and for in JS, help me!

brendalimon

Brenda Limón

Posted on August 12, 2018

Cycles while and for in JS, help me!

Hi! I'm trying to learn how to draw in Canvas, as an exercise to learn about cycles in JS, the exercise is that we have to use while to create a cycle and draw this:

Alt text of image

Everything was okay, my code is like this:

**var d= document.getElementById("dibujito");**
**var lienzo= d.getContext("2d");**
**var lineas = 30;**
**var l = 0;**
**var yi, xf;**
**var colorcito = "pink";**


**while(l < lineas)**
**{**
 ** yi = 10 * l;**
  **xf = 10 * (l+1);**
  **dibujarLinea(colorcito, 0,yi,xf,300);**
  **console.log("Linea " + l)**
  **l = l + 1;**
**}**


**dibujarLinea(colorcito,299,1,299,299);**
**dibujarLinea(colorcito,1,1,299,1);**
**dibujarLinea(colorcito,1,1,1,299);**
**dibujarLinea(colorcito,1,299,299,299);**

**function dibujarLinea(color,xinicial,yinicial,xfinal,yfinal)**
**{**
  **lienzo.beginPath();**
  **lienzo.strokeStyle = color;**
  **lienzo.moveTo(xinicial,yinicial);**
  **lienzo.lineTo(xfinal,yfinal);**
  **lienzo.stroke();**
  **lienzo.closePath();**
**}**
Enter fullscreen mode Exit fullscreen mode

But the problem comes when I have to turn the draw like this with for

Alt text of image

I just don't understand how to use for, I've already tried to make the code work but I can't, can you explain to me how to make it work? Thanks!

Hugs & Husky love!🐶👩🏻‍💻

💖 💪 🙅 🚩
brendalimon
Brenda Limón

Posted on August 12, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related