I'm writing a fadeIn function for an HTMLElement, the animation works but it's a bit choppy at the moment. what it does is animate a fadeIn from 0 opacity to 1, it also animates over a duration using requestFrameAnimation that's why it's probably so choppy, can someone help me make my animation run more smoothly. and example is on codepen.io look at the header fadeIn and see what I mean
fadeIn: function(duration) {
var el = this.$el,
duration,
end = 0;
el.style.opacity = 0;
el.style.display = "block";
var step = function() {
var current = +new Date(),
remaining = end - current;
if(remaining < 60) {
if(el) {
end = current + duration;
var val = parseFloat(el.style.opacity);
if (!((val += .1) > 1)) {
el.style.opacity = val;
}
} else {
return;
}
}
requestAnimationFrame(step);
};
step();
},
答案 0 :(得分:2)
The smoothest one you can do is using CSS transition. But if you want to do with pure Javascript, you can do something like this
function fadeIn(dom, duration) {
let start = null;
const step = (end) => {
if (start === null) start = end;
let dt = end - start;
dom.style.opacity = Math.min(1, dt / duration);
if (dt < duration) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
function fadeOut(dom, duration) {
let start = null;
const step = (end) => {
if (start === null) start = end;
let dt = end - start;
dom.style.opacity = Math.max(0, 1 - dt / duration);
if (dt < duration) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
fadeIn(document.getElementById('your_dom'), 2000);