简体   繁体   中英

Oscillate values of image filter in HTML

I'm trying to change the saturate filter value from 1 to 5 and back to 1. I'm guessing the implementation of a variable in the getElementById is completely wrong. What's the problem?

 var up = true; var value = 1; var increment = 1; var ceiling = 5; function PerformCalc() { if (up == true && value <= ceiling) { value += increment if (value == ceiling) { up = false; } } else { up = false value -= increment; if (value == 1) { up = true; } } function changesaturation(value) { document.getElementById("s1").style.webkitFilter = "saturate(" value")"; } } setInterval(PerformCalc, 100);
 <img src="image.jpg" id="s1" width="100%" height="1200px">

The nested function "changesaturation" doesn't seem necessary.
Also, string concatenation in JavaScript can be achieved with the Addition (+) operator.
Other than that, your code seems to work.

 var up = true; var value = 1; var increment = 1; var ceiling = 5; function PerformCalc() { if (up == true && value <= ceiling) { value += increment if (value == ceiling) { up = false; } } else { up = false value -= increment; if (value == 1) { up = true; } } document.getElementById("s1").style.webkitFilter = "saturate(" + value + ")"; } setInterval(PerformCalc, 100);
 #s1 { width:250px; }
 <img src="https://i.picsum.photos/id/1069/536/354.jpg?hmac=ywdE7hQ_NM4wnxJshRkXBsy-MHlGRylyqlb51WToAQA" id="s1">

As Temani Afif mentioned , the effect can also be achieved with CSS animation .
Here's an example:

 @-webkit-keyframes pulseSaturate { 0% { -webkit-filter: saturate(1); } 50% { -webkit-filter: saturate(5); } 100% { -webkit-filter: saturate(1); } } @keyframes pulseSaturate { 0% { filter: saturate(1); } 50% { filter: saturate(5); } 100% { filter: saturate(1); } } #s1 { width: 250px; -webkit-animation: pulseSaturate 800ms steps(4, end) infinite; animation: pulseSaturate 800ms steps(4, end) infinite; }
 <img src="https://i.picsum.photos/id/1069/536/354.jpg?hmac=ywdE7hQ_NM4wnxJshRkXBsy-MHlGRylyqlb51WToAQA" id="s1">

According to shouldiprefix , the "-webkit"vendor prefix is recommended at the time of this post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM