简体   繁体   中英

setTimeout() and canvas not working as intended

Here's my code. I created a VIBGOYR pattern on the canvas and want to change the radial gradient of the system after a time interval so that it looks animated.

function activate(index){
  canvas =document.getElementById("exp");
  context = canvas.getContext('2d');

  //Start.
  draw(index);

  //Functions.
    function draw(index){
      drawGradiantSq(index);
      var t=setTimeout(doTimer,1000);
  }

  function doTimer(){
      draw(index+10);
  }

  function drawGradiantSq(fi){
      console.log(fi);
      var g1 = context.createRadialGradient(0,300,0,500,300,fi);
      colors = ["violet","indigo","blue","green","orange","yellow","red"];
      var x= 1/12;

      for (var i=0;i<colors.length;i++){
          g1.addColorStop(i*x,colors[i]);
      }
      context.fillStyle = g1;
      context.fillRect(0,0,500,600);

      var g2 = context.createRadialGradient(1000,300,0,500,300,fi);

      for (var i=0;i<colors.length;i++){
          g2.addColorStop(i*x,colors[i]);
      }
      context.fillStyle = g2;
      context.fillRect(500,0,1000,600);
  }
}


But the output i'm getting only changes the gradient only once although the timer seems to be working fine. The HTML file:

<body>
    <canvas id="exp" width="1000px" height="600px"></canvas>
    <button onclick="activate(index+=10);">Paint</button>
</body>

The variable index is a global variable set to 0.

Try using setInterval instead of setTimeout .

setTimeout is only triggered once: 'setInterval' vs 'setTimeout'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM