Link to home
Start Free TrialLog in
Avatar of derrida
derrida

asked on

a method works but freezes the browser

hi
i have a method that manipulate a canvas image to add noise. it does work but it freezes the browser for at least a minute and a half.
the amount is set while dragging a slider. again work but obviously doesn't give a good user experience. maybe there is a way to make it perform better, to optimize it?

here is the method:
  setNoise(opacity){

    opacity = opacity || .2;

    for (var x = 0; x < this.thecanvas.width; x++ ) {
        for (var y = 0; y < this.thecanvas.height; y++ ) {
          let number = Math.floor( Math.random() * 60 );
  
          this.thecontext.fillStyle = "rgba(" + number + "," + number + "," + number + "," + opacity + ")";
          this.thecontext.fillRect(x, y, 1, 1);
        }
    }

    let dData = this.getData();
    this.setData(dData)
  }

Open in new window

Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

I think that your problem is the opacity argument that takes the function from slider.Check the grading of the slider not to be very very small eg for every pixel move to increase or decrease the opacity each 0.1 I made a test in a similar code  and when I put increment 0.001 the function was running for about 5 min
See the example code below:
function generateNoise(opacity) {
   if ( !!!document.createElement('canvas').getContext ) {
      return false;
   }
 
   var canvas = document.createElement("canvas"),
   ctx = canvas.getContext('2d'),
   x, y,
   number,
   opacity = opacity || .2;
 
   canvas.width = 45;
   canvas.height = 45;
 
   for ( x = 0; x < canvas.width; x++ ) {
      for ( y = 0; y < canvas.height; y++ ) {
         number = Math.floor( Math.random() * 60 );
 
         ctx.fillStyle = "rgba(" + number + "," + number + "," + number + "," + opacity + ")";
         ctx.fillRect(x, y, 1, 1);
      }
   }
 
   document.body.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")";
}

for(var i=0.1;i<=0.9;i+=0.01){
  generateNoise(i);
  console.log(i);
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of derrida
derrida

ASKER

i actually did used the getImageData and  putImageData at the end with the get and set, BUT i didn't wrapped it AND your calculation is way better than mine was. now it runs very smooth!!! thanks for the help