Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
How do you make a loop for canvas function which has several arguments?
<canvas id="chart" width="700" height="550"></canvas>

<script>
  const canvas = document.getElementById('chart');
  const context = canvas.getContext('2d');

  /* Draw a line from (fromX, fromY) to (toX, toY) */
  function drawLine(fromX, fromY, toX, toY) {
    context.beginPath();
    context.moveTo(toX, toY);
    context.lineTo(fromX, fromY);
    context.stroke();
  }

  /* Draw a text (string) on (x, y) */
  function drawText(text, x, y) {
    context.fillStyle = 'black';
    context.fillText(text, x, y);
  }

  /* Draw a text and with a line to its right */
  function drawLineWithText(text, fromX, fromY, toX, toY) {
    drawText(text, fromX - 50, fromY + 3);
    drawLine(fromX, fromY, toX, toY);
  }

  for (var fromY = 50; fromY < 500; fromY += 50, toY = 50 toY < 500; toY += 50, fromX = 70, toX =700) {
    drawLineWithText(text, fromX, fromY, toX, toY);
  }
</script>
**strong text** I actually have no clue how to make a for statement for this, I tried to play around, but only managed to make it work when I did it manually, writing own arguments example; drawLineWithText(1000, 20, 30, 100, 30)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

On this case I do not see anything special that will require multiple variables in a for loop...
If we break down what you have inside your loop, we end up with:

/*
    fromY = 50; fromY < 500; fromY += 50, 
      toY = 50;   toY < 500;   toY += 50, 

    fromX = 70, 
      toX = 700
*/

The fromY and toY have the same pattern, and fromX and toX have just hardcode values...

So to simplify your code this is what I would do:

const canvas = document.getElementById('chart');
const context = canvas.getContext('2d');

function drawLine(fromX, fromY, toX, toY) {
  context.beginPath();
  context.moveTo(toX, toY);
  context.lineTo(fromX, fromY);
  context.stroke();
}

for (var i = 50; i < 500; i += 50) {
  drawLine(70, i, 700, i);
}
<canvas id="chart" width="700" height="550"></canvas>




You can have multiple variables in a loop, that is absolutely possible, but your sample is not the best use for it, here is a good example for multiple variables.

const canvas = document.getElementById('chart');
const context = canvas.getContext('2d');

function drawLine(fromX, fromY, toX, toY) {
  context.beginPath();
  context.moveTo(toX, toY);
  context.lineTo(fromX, fromY);
  context.stroke();
}

var x, y
for (x=50, y=10;  x<200, y<100;  x*=1.3, y+=9) {
  drawLine(10, y/3, x, y);
}
<canvas id="chart" width="500" height="100"></canvas>

Here some good reading about the anatomy of a for loop:
https://gomakethings.com/the-anatomy-of-a-for-loop-in-vanilla-js-and-when-you-would-want-to-use-it-instead-of-array.foreach/

...It’s broken up into three parts, each separated by a semicolon (;):

  • Before the first semicolon, you can declare or assign variables.
  • Between the first and second semicolon, you define a condition to check after each loop. As long as this condition is true, the loop keeps running. Once the condition is false, the loop stops.
  • After the second semicolon, you can specify a statement to run after each loop.
about 4 years ago · Juan Pablo Isaza Relatório

0

Try collecting your custom arguments into a single array that can be iterated over first. Possibly something like this:

// establish your starts, ends, and steps
const text = 'Some text';

const fromXStart = 70;
const fromXEnd = 700;
const fromXStep = 50;

const fromYStart = 50;
const fromYEnd = 500;
const fromYStep = 50;

const toXStart = 700;
const toXEnd = 1000;
const toXStep = 50;

const toYStart = 50;
const toYEnd = 500;
const toYStep = 50;

// create an object to keep track of where we are at each iteration of the loop
const currentArgs = {
  fromX: fromXStart,
  fromY: fromYStart,
  toX: toXStart,
  toY: toYStart
}

// create a single array of args to loop over with our intial values
const args = [
  [text, currentArgs.fromX, currentArgs.fromY, currentArgs.toX, currentArgs.toY]
]

// create a check function to see if we're done looping (if all ends have been met)
const isDone = () => {
  const fromXIsDone = currentArgs.fromX >= fromXEnd;
  const fromYIsDone = currentArgs.fromY >= fromYEnd;
  const toXIsDone = currentArgs.toX >= toXEnd;
  const toYIsDone = currentArgs.toY >= toYEnd;
  return fromXIsDone && fromYIsDone && toXIsDone && toYIsDone;
}

// loop until done
while (!isDone()) {
  // use Math.min to ensure we don't go past the max
  currentArgs.fromX = Math.min(fromXEnd, currentArgs.fromX + fromXStep);
  currentArgs.fromY = Math.min(fromYEnd, currentArgs.fromY + fromYStep);
  currentArgs.toX = Math.min(toXEnd, currentArgs.toX + toXStep);
  currentArgs.toY = Math.min(toYEnd, currentArgs.toY + toYStep);
  args.push([
    text, currentArgs.fromX, currentArgs.fromY, currentArgs.toX, currentArgs.toY
  ])
}

// now loop over our args array and use the spread syntax (...) to spread the args as args
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
for (let i = 0; i < args.length; i++) {
  drawLineWithText(...args[i]);
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda