javascripthtmlcssimageblur

Is there a way in javascript to reduce the blur of an image in steps through a loop and a variable?


I am trying something like this:

let str = 10;
let blu = "px";
let val = "";

function check() {
    if(a < b){
    str = str - 6;
    if (str<0){str = 0}
    val = str+blu;
    document.getElementById("img1").`style.filter = 'blur(val)';
}

Here the value of 'str' and hence 'val' changes everytime the function 'check' is run, but 'blur(val)' gives an error.

I was expecting that a variable can be used here. I also tried setProperty. document.getElementById("img1").style.setProperty("blur", val); but this also gives error.

What is the solution? Also, how do you reduce the blur of a text or a image according to a timer. For example, if the initial blur is set to 60px, every passing second, the blur reduces by 1 px, and finally after 1 minute, entire text is clearly visible?


Solution

  • Yes, but why not use a CSS transition instead? Simple and smooth.

    document.querySelector('button').addEventListener('click', () => {
      document.querySelector('.i1').classList.toggle('blur')
    })
    .i1 {
      display: block;
      margin: 3em auto 0;
      transition: 2s;
    }
    
    .i1.blur {
      filter: blur(20px);
    }
    wait for image to load, then <button>toggle blur</button>
    <img class="i1" src="http://picsum.photos/300/100">