Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
Javascript Canvas opacity gets stronger with setinterval

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);
    }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!