<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> **texto fuerte** De hecho, no tengo idea de cómo hacer una declaración for para esto, traté de jugar, pero solo logré hacerlo funcionar cuando lo hice manualmente, escribiendo mis propios argumentos de ejemplo; dibujarLíneaConTexto(1000, 20, 30, 100, 30)En este caso, no veo nada especial que requiera múltiples variables en un bucle for...
Si desglosamos lo que tiene dentro de su ciclo, terminamos con:
/* fromY = 50; fromY < 500; fromY += 50, toY = 50; toY < 500; toY += 50, fromX = 70, toX = 700 */ fromY y toY tienen el mismo patrón, y fromX y toX solo tienen valores de código fijo...
Entonces, para simplificar su código, esto es lo que haría:
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>Puede tener múltiples variables en un ciclo, eso es absolutamente posible, pero su muestra no es el mejor uso para ella, aquí hay un buen ejemplo para múltiples 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> Aquí hay una buena lectura sobre la anatomía de un bucle for:
https://gomakethings.com/the-anatomy-of-a-for-loop-in-vanilla-js-and-when-you-would-want-to-use-it-instead-of-array.foreach/
...Se divide en tres partes, cada una separada por un punto y coma (;):
- Antes del primer punto y coma, puede declarar o asignar variables.
- Entre el primer y el segundo punto y coma, define una condición para verificar después de cada ciclo. Siempre que esta condición sea verdadera, el ciclo continúa ejecutándose. Una vez que la condición es falsa, el ciclo se detiene.
- Después del segundo punto y coma, puede especificar una declaración para que se ejecute después de cada ciclo.
Intente recopilar sus argumentos personalizados en una sola matriz que se pueda iterar primero. Posiblemente algo como esto:
// 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]); }