最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Changing CSS transform on scroll: jerky movement vs. smooth movement - Stack Overflow

programmeradmin4浏览0评论

I'm dissatisfied with existing parallax libraries, so I'm trying to write my own. My current one consists of three main classes:

  • ScrollDetector tracks an element's scroll position relative to the screen; it has functions to return a float representing its current position:
    • 0 represents the top edge of the element being at the bottom edge of the viewport
    • 1 represents the bottom edge of the element being at the top edge of the viewport
    • All other positions are interpolated/extrapolated linearly.
  • ScrollAnimation uses a ScrollDetector instance to interpolate arbitrary CSS values on another element, based on the ScrollDetector element.
  • ParallaxativeAnimation extends ScrollAnimation for the special case of a background image that should scroll at a precise factor of the window scroll speed.

My current situation is this:

  • ScrollAnimations using transform: translateY(x) work smoothly.
  • ParallaxativeAnimations using translateY(x) work, but animate jerkily.
  • ParallaxativeAnimations using translate3d(0, x, 0) are jerky, but not as badly.
  • The Rellax library's animations, which use translate3d(0, x, 0), work perfectly smoothly.

You can see the comparison on this pen. (The jerkiness shows up best in Firefox.) My library is on Bitbucket.

I don't know where the problem in my library lies and I don't know how to figure it out. Here is an abridged paste of where the heavy lifting is done while scrolling in the ScrollAnimation class that works smoothly:

getCSSValue(set, scrollPosition) {
    return set.valueFormat.replace(set.substitutionString, ((set.endValue - set.startValue) * scrollPosition + set.startValue).toString() + set.unit)
}

updateCSS() {
    var cssValues = [];

    var scrollPosition = this.scrollDetector.clampedRelativeScrollPosition();

    var length = this.valueSets.length;
    for(var i = 0; i < length; i++) {
        cssValues.push(getCSSValue(valueSets[i], scrollPosition) );
    }

    this.setCSS(cssValues);
    this.ticking = false;
}

requestUpdate() {
    if(!this.ticking) {
        requestAnimationFrame(() => { this.updateCSS(); });
    }

    this.ticking = true;
}

And here's the equivalent in the ParallaxativeAnimation class that is jerky:

updateCSS() {
    var scrollPosition = this.scrollDetector.clampedRelativeScrollPosition();
    var cssValues = [];

    var length = this.valueSets.length;
    for(var i = 0; i < length; i++) {
        var scrollTranslate = -((this.scrollTargetSize - this.valueSets[i].parallaxSize) * scrollPosition);

        cssValues.push(
            this.valueSets[i].valueFormat.replace(this.valueSets[i].substitutionString, scrollTranslate.toString() + 'px')
        );
    }

    this.setCSS(cssValues);
    this.ticking = false;
}

requestUpdate() {
    if(!this.ticking) {
        requestAnimationFrame(() => { this.updateCSS(); });
    }

    this.ticking = true;
}

The math doesn't seem any more complicated, so I can't figure how that's affecting animation performance. I thought the difference might have been my styling on the parallax image, but in the pen above, the Rellax version has the exact same CSS on it, but animates perfectly smoothly. Rellax seems to maybe be doing more complicated math on each frame:

var updatePosition = function(percentage, speed) {
  var value = (speed * (100 * (1 - percentage)));
  return self.options.round ? Math.round(value) : Math.round(value * 100) / 100;
};


//
var update = function() {
  if (setPosition() && pause === false) {
    animate();
  }

  // loop again
  loop(update);
};

// Transform3d on parallax element
var animate = function() {
  for (var i = 0; i < self.elems.length; i++){
    var percentage = ((posY - blocks[i].top + screenY) / (blocks[i].height + screenY));

    // Subtracting initialize value, so element stays in same spot as HTML
    var position = updatePosition(percentage, blocks[i].speed) - blocks[i].base;

    var zindex = blocks[i].zindex;

    // Move that element
    // (Set the new translation and append initial inline transforms.)
    var translate = 'translate3d(0,' + position + 'px,' + zindex + 'px) ' + blocks[i].transform;
    self.elems[i].style[transformProp] = translate;
  }
  self.options.callback(position);
};

The only thing I can really tell from Chrome Developer Tools is that the framerate isn't dipping too far below 60 fps, so maybe it's not that I'm doing too much work each frame, but that I'm doing something mathematically incorrect when I calculate the position?

So I don't know. I'm clearly in way over my head here. I'm sorry to throw a whole library at StackOverflow and say "FIX IT", but if anyone can tell what I'm doing wrong, or tell me how to use Developer Tools to maybe figure out what I'm doing wrong, I'd appreciate it very much.


EDIT

Okay, I've figured out that the most important factor in the jitteriness of the scrolling is the height of the element being translated. I had a miscalculation in my library that was causing the background images to be much taller than they needed to be when my scrollPixelsPerParallaxPixel property was high. I'm in the process of trying to correct that now.

I'm dissatisfied with existing parallax libraries, so I'm trying to write my own. My current one consists of three main classes:

  • ScrollDetector tracks an element's scroll position relative to the screen; it has functions to return a float representing its current position:
    • 0 represents the top edge of the element being at the bottom edge of the viewport
    • 1 represents the bottom edge of the element being at the top edge of the viewport
    • All other positions are interpolated/extrapolated linearly.
  • ScrollAnimation uses a ScrollDetector instance to interpolate arbitrary CSS values on another element, based on the ScrollDetector element.
  • ParallaxativeAnimation extends ScrollAnimation for the special case of a background image that should scroll at a precise factor of the window scroll speed.

My current situation is this:

  • ScrollAnimations using transform: translateY(x) work smoothly.
  • ParallaxativeAnimations using translateY(x) work, but animate jerkily.
  • ParallaxativeAnimations using translate3d(0, x, 0) are jerky, but not as badly.
  • The Rellax library's animations, which use translate3d(0, x, 0), work perfectly smoothly.

You can see the comparison on this pen. (The jerkiness shows up best in Firefox.) My library is on Bitbucket.

I don't know where the problem in my library lies and I don't know how to figure it out. Here is an abridged paste of where the heavy lifting is done while scrolling in the ScrollAnimation class that works smoothly:

getCSSValue(set, scrollPosition) {
    return set.valueFormat.replace(set.substitutionString, ((set.endValue - set.startValue) * scrollPosition + set.startValue).toString() + set.unit)
}

updateCSS() {
    var cssValues = [];

    var scrollPosition = this.scrollDetector.clampedRelativeScrollPosition();

    var length = this.valueSets.length;
    for(var i = 0; i < length; i++) {
        cssValues.push(getCSSValue(valueSets[i], scrollPosition) );
    }

    this.setCSS(cssValues);
    this.ticking = false;
}

requestUpdate() {
    if(!this.ticking) {
        requestAnimationFrame(() => { this.updateCSS(); });
    }

    this.ticking = true;
}

And here's the equivalent in the ParallaxativeAnimation class that is jerky:

updateCSS() {
    var scrollPosition = this.scrollDetector.clampedRelativeScrollPosition();
    var cssValues = [];

    var length = this.valueSets.length;
    for(var i = 0; i < length; i++) {
        var scrollTranslate = -((this.scrollTargetSize - this.valueSets[i].parallaxSize) * scrollPosition);

        cssValues.push(
            this.valueSets[i].valueFormat.replace(this.valueSets[i].substitutionString, scrollTranslate.toString() + 'px')
        );
    }

    this.setCSS(cssValues);
    this.ticking = false;
}

requestUpdate() {
    if(!this.ticking) {
        requestAnimationFrame(() => { this.updateCSS(); });
    }

    this.ticking = true;
}

The math doesn't seem any more complicated, so I can't figure how that's affecting animation performance. I thought the difference might have been my styling on the parallax image, but in the pen above, the Rellax version has the exact same CSS on it, but animates perfectly smoothly. Rellax seems to maybe be doing more complicated math on each frame:

var updatePosition = function(percentage, speed) {
  var value = (speed * (100 * (1 - percentage)));
  return self.options.round ? Math.round(value) : Math.round(value * 100) / 100;
};


//
var update = function() {
  if (setPosition() && pause === false) {
    animate();
  }

  // loop again
  loop(update);
};

// Transform3d on parallax element
var animate = function() {
  for (var i = 0; i < self.elems.length; i++){
    var percentage = ((posY - blocks[i].top + screenY) / (blocks[i].height + screenY));

    // Subtracting initialize value, so element stays in same spot as HTML
    var position = updatePosition(percentage, blocks[i].speed) - blocks[i].base;

    var zindex = blocks[i].zindex;

    // Move that element
    // (Set the new translation and append initial inline transforms.)
    var translate = 'translate3d(0,' + position + 'px,' + zindex + 'px) ' + blocks[i].transform;
    self.elems[i].style[transformProp] = translate;
  }
  self.options.callback(position);
};

The only thing I can really tell from Chrome Developer Tools is that the framerate isn't dipping too far below 60 fps, so maybe it's not that I'm doing too much work each frame, but that I'm doing something mathematically incorrect when I calculate the position?

So I don't know. I'm clearly in way over my head here. I'm sorry to throw a whole library at StackOverflow and say "FIX IT", but if anyone can tell what I'm doing wrong, or tell me how to use Developer Tools to maybe figure out what I'm doing wrong, I'd appreciate it very much.


EDIT

Okay, I've figured out that the most important factor in the jitteriness of the scrolling is the height of the element being translated. I had a miscalculation in my library that was causing the background images to be much taller than they needed to be when my scrollPixelsPerParallaxPixel property was high. I'm in the process of trying to correct that now.

Share Improve this question edited Nov 20, 2017 at 17:36 Lanny Heidbreder asked Nov 15, 2017 at 19:45 Lanny HeidbrederLanny Heidbreder 1,40316 silver badges29 bronze badges 11
  • 4 Two things: To do a fair comparison of the two versions of your library you should apply them to identical elements. Comparing the scrolling performance of a heading against the scrolling performance of a large background image isn't a fair comparison. I would like to see both versions operating on a background image. Secondly, I notice that Rellax applies a translate3d() transform to the scrolling element, whereas you apply a translateY(). This could affect performance, since translate3d() will force the browser to offload rendering to the GPU. – Jonathan Nicol Commented Nov 19, 2017 at 23:19
  • 1 A follow up on my previous comment: translate3d() doesn't seem to improve the scroll jank. Another thing to consider is how frequently you are measuring elements. I looks like you are calling getBoundingClientRect() every redraw. You should only need to measure the element initially and when a resize has occurred. Ideally the only measurement you should make each redraw is window.scrollY. – Jonathan Nicol Commented Nov 20, 2017 at 1:28
  • 1 You're not changing the height of the image mid-scroll though are you? On another note, and you probably know this already, but scroll jank is very common when the element being scrolled has any position value other than fixed. IMO that is the #1 factor that makes parallax so tricky, since fixing the element to the viewport causes all kinds of other layout headaches. – Jonathan Nicol Commented Nov 20, 2017 at 18:55
  • 1 Unless I'm doing something very wrong by accident, I'm only updating the image's height on resize. And yeah, I tried doing position: fixed, and it would have worked if that didn't make a new stacking context no longer masked by its parent's being overflow: hidden. – Lanny Heidbreder Commented Nov 20, 2017 at 21:10
  • 1 Parallax is a PITA for sure! In your case I believe the browser sometimes sneaks in a redraw before the translate is applied, so for a split second you see the element in its pre-translate position. As you have observed, the jitter is less obvious with small scroll values, which is possibly why Rellax internally clamps the parallax movement to a very small value. Fixed position elements don't have the same problem since they don't move when the page is scrolled, only when the translate is applied. – Jonathan Nicol Commented Nov 20, 2017 at 22:15
 |  Show 6 more comments

3 Answers 3

Reset to default 6

You are able to get a visual performance boost by implementing will-change on elements. It is supported in recent browsers (excluding edge and no IE).

The will-change CSS property hints to browsers how an element is expected to change. Browsers may set up optimizations before an element is actually changed. These kinds of optimizations can increase the responsiveness of a page by doing potentially expensive work before they are actually required.

You can either impelment it like:

function gogoJuice() {
  // The optimizable properties that are going to change
  self.elems[i].style.willChange = 'transform';
}

function sleepNow() {
  self.elems[i].style.willChange = 'auto';
}

Or more basically just in the css on the element which you are changing:

.parallax {
  will-change: transform;
}

This property is intended as a method for authors to let the user-agent know about properties that are likely to change ahead of time. Then the browser can choose to apply any ahead-of-time optimizations required for the property change before the property change actually happens. So it is important to give the the browser some time to actually do the optimizations. Find some way to predict at least slightly ahead of time that something will change, and set will-change then.

Aside from the calculations, you could try running it asynchronously by using Promise:

await Promise.all([
  loop(update);
]);

just to see if it has a positive impact on the performance.

I'd comment, but I don't have enough reputation yet.

You want to avoid touching the DOM or changing anything on the screen

发布评论

评论列表(0)

  1. 暂无评论