Home > Software engineering >  Javascript Canvas opacity gets stronger with setinterval
Javascript Canvas opacity gets stronger with setinterval

Time:08-29

I have the following script, which draws red rectangles on canvas and the problem is the rectangles gets stronger opacity in time. Why?

HTML:

<canvas id="myCanvas" width="500" height="150" style="border:1px solid black;">
</canvas>

Javascript:

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

    const inter = setInterval(start, 1000);
    i = 0;
    myarr = [];
    
    function drawarray(arr){
    
      for ( var k = 0; k<arr.length; k  ){
        // I tried to use Math random, but it also don't work
        // I tried rgba, but also don't work
        ctx.globalAlpha = 0.2;
        ctx.fillStyle = "red";
        ctx.fillRect(canvas.width-90-i*50,arr[k][0]*5,10,2);
      }
    }
    
    function start() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        for ( var e=0; e<10;e  ){
            myarr.push([e,Math.random().toFixed(1)]);
        }
        drawarray(myarr);
        i  ;
    
    }
    
    function stop() {
      clearInterval(inter);
    }

CodePudding user response:

Empty out "myarr" after you do the drawing. What's happening is you're drawing 10 rectangles, then 20, then 30, and so on.

  • Related