javascriptcolorshtml5-canvascurves

I used a for loop to draw different curves. But how can I change every line to a different color?


In my draw function I draw everything. I draw the white rect because you can change the position of every curve and otherwise you will see all of them. Not just the one with your new position.

function draw() {
    var canvasWidth = canvas.width;
    var canvasHeight = canvas.height;

    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, canvasWidth, canvasHeight); 

    for (var i = 0; i <= line.length; i++) {    

            // Directly under this line of text stands my color for the 
            // curves and that is what needs to be corrected I guess.
            ctx.strokeStyle = "rgb(200,200,200)";
            ctx.beginPath();
            ctx.moveTo(500, 150);
            ctx.bezierCurveTo(line[i], 300, line[i], 300, line[i], 400 + (i * 15));
            ctx.stroke();
            ctx.closePath();

        console.log[i];
    }
}

The function below gets the values of my from out my html so it can draw the correct curves

function create(){
    console.log("change line");
    var form = document.getElementById("frm1");

    for(var i = 0; i < form.length; i++){
        line[i] = form[i].value;
    }

    console.log(line);
    draw();
}

Solution

  • you can use a function like this:

    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    

    to retrieve a random number between 0 and 255 for each value of R,G and B (red green and blue). So I'd write your code as

    red = getRandomInt(0,255);
    green = getRandomInt(0,255);
    blue = getRandomInt(0,255);
    ctx.strokeStyle = "rgb("+red+","+green+","+blue+")";
    

    hope it helps!