Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blur an image with JavaScript

I want to make something like a Slideshow, but if you press a button for the next Picture, it should blur out until its unrecognizeable and then the next should appear blurred and become sharp. Problem here is, i would have to apply the blur via JS and my current approach looks like this: document.getElementById("no1").style.filter = "blur(3Px)";

If i apply the blur with css it works just fine, but i need it to apply when the button is clicked, which does not work. The obejct i am trying to blur is an <img>

Also, it would be good to know, if there is something like a waiting condition or if additional steps in the function will wait for the transition duration of the blur to be done before starting.

like image 533
FrozenYoghurt Avatar asked May 27 '20 09:05

FrozenYoghurt


People also ask

How do I blur an image in Javascript?

It really isn't much more <script> function blur() { document. getElementById("no1"). style. filter = "blur(3Px)"; } </script> I'm building the function step by step and that usually works out for me.

How do you blur the background in Javascript?

Window blur() The blur() method removes focus from a window. The focus() method sets focus to a window.

How do you blur an image?

If you take a picture in Portrait mode, open it in the Photos app, tap Edit, and then tap the f button at the top left. Use the slider to change the blur effect.

How do you blur in CSS?

Syntax. filter: blur(px); To apply a blur effect to the background image, with the blur function use the z-index property to set the stack order of the element, set the width and height 100% to have a full background image.


1 Answers

const img = document.querySelector('img');
img.addEventListener('click', toggleBlur);

function toggleBlur() {
  this.classList.toggle('blur');
}
img { transition: filter 1s linear; }
.blur { filter: blur(30px); }
<img src="https://i.imgur.com/KjUybBD.png"></img>

Works for me in Chrome, Firefox, Safari, latest Edge...

enter image description here

like image 119
gman Avatar answered Sep 20 '22 13:09

gman