0

I'm trying to draw a bunch of curves but I want to be able to show the process of drawing step by step. When I use setTimeout javascript only draws a single segment and stops. Here is the code:

function drawFlower(slow=false){
    let diameter=cfg.diameter;
    let amp=cfg.amp;
    let line_width = cfg.line_width;
    let opacity = cfg.opacity;
    let ctx = cfg.ctx;
    let cs = cfg.color_scale
    let flower = cfg.flower;
    let colors = cfg.colors;
    const num_points = flower[0].length;
    const num_samples = flower.length;


    ctx.fillStyle = cfg.bgcolor;
    ctx.fillRect(0, 0, cfg.canvas.width, cfg.canvas.height);
    for(let i=0;i<num_samples-1;i++){
        for(let j=0; j<num_points;j++){
            let r1 = 0.1+(diameter+amp*flower[i][j])*i/num_samples;
            let r2 = 0.1+(diameter+amp*flower[i][(j+1)%num_points])*i/num_samples;

            let theta1 = 2*Math.PI*j/(num_points);
            let theta2 = 2*Math.PI*((j+1))/(num_points);
            let x1 = 450+r1*Math.cos(theta1);
            let x2 = 450+r2*Math.cos(theta2);
            let y1 = 450+r1*Math.sin(theta1);
            let y2 = 450+r2*Math.sin(theta2);

            ctx.beginPath(); 
            ctx.moveTo(x1,y1);
            ctx.lineTo(x2,y2);

            let cols = [cs*256*colors[i][0],cs*256*colors[i][1],cs*256*colors[i][2]];
            cols = rgbToHsl(...cols);
            cols = hslToRgb(cfg.hue_shift+cols[0]-Math.floor(cfg.hue_shift+cols[0]), cfg.saturation*cols[1], cfg.brightness*cols[2]);

            ss = `rgba(${cols[0]},${cols[1]},${cols[2]},${opacity*i/num_samples})`;

            ctx.strokeStyle = ss;
            ctx.lineWidth = line_width;
            if(slow){
                setTimeout(()=>{ctx.stroke},100)
            }
            else{
                ctx.stroke();
            }
    }
}
}

in particular, this part is supposed to make gradual drawing happen:

if(slow){
     setTimeout(()=>{ctx.stroke},100)}
else{
     ctx.stroke();}

I have seen workarounds using requestAnimationFrame but I'm curious why this does not work. The result with slow=false(left) and slow=true(right) look like this: enter image description here

MostafaMV
  • 2,181
  • 3
  • 16
  • 22

0 Answers0