How do I change the line thickness on canvas according to an interval?

0

I want to create a canvas element that changes the thickness of the border every 3 seconds, that has a thickness of line 5px starting, 3 seconds later has another thickness of 10px, after 3 seconds start again in thickness 5px. That is, it is in an infinite loop instead of border thickness. Any suggestions?

var c=document.getElementById("myCanvas");
      var ctx=c.getContext("2d");

      ctx.strokeStyle="red";
      ctx.lineWidth=5;
      ctx.strokeRect(20,20,100,100);

      setTimeout(function() {
          ctx.clearRect(20,20,100,100);
          //ctx.strokeStyle="black";
          ctx.lineWidth=10;
          ctx.strokeRect(20,20,100,100);
      }, 3000);
    
asked by mestanza 12.02.2018 в 16:26
source

1 answer

0

You can use setInterval to execute the function every 3 seconds and use an external flag to establish what width to draw with:

var c=document.getElementById("myCanvas");
      var ctx=c.getContext("2d");
      ctx.strokeStyle="red";

      var flag = true;
      function dibujar() {
          ctx.clearRect(20,20,100,100);
          ctx.lineWidth=  flag ? 5 : 10;
          flag = !flag;
          ctx.strokeRect(20,20,100,100);
      }
      // Dibujo inicial
      dibujar();
      // Repetir cada 3 s
      setInterval(dibujar, 3000);
<canvas id="myCanvas" width="200" height="200"></canvas>
    
answered by 12.02.2018 / 16:36
source