8

I'm trying to control a video by scrolling so that as the user moves down the page, the video moves with their scrolling. I do this by adding an event handler to the scroll event, which updates the video element's currentTime attribute. When using Safari (11.0.2), the animation is smooth but on Chrome (63) or Firefox, the frame only updates at the end of an inertial scroll. I am able to smooth the animation by lowering the video's horizontal resolution to 600px. Is this simply a product of differing performance or is does my code have some browser-specific optimisation issues?

Note: I tested using a Mac with multitouch smooth scrolling. Not sure if the behaviour is less pronounced with a scroll wheel.

Below is the js used and a link to an example:

var total, video;
window.onload = function() {
  video = document.getElementById("video");

  // Should react to scrolling until halfway down the video.
  total = video.scrollHeight/2 + document.getElementById('top').scrollHeight;
  window.addEventListener("scroll", animateGoat, false);
};

function animateGoat(ev) {
  var scroll = window.pageYOffset ||
    document.documentElement.scrollTop ||
    document.body.scrollTop || 0;
  // Updates the video to the time with the same fraction of completion as the scroll.
  video.currentTime = scroll <= total ? 2 * scroll / total : 2;
}

https://codepen.io/anon/pen/gVbNNQ

2
  • Did you ever find an answer for this? Commented Jul 19, 2019 at 18:39
  • 1
    @QuinnKeaveney sorry to say but I did not! I assume it's just because Safari is better optimised on Mac.
    – Amja
    Commented Jul 19, 2019 at 22:04

1 Answer 1

15

I believe the choppiness has to do with the way the in which the video itself is encoded.

Using ffmpeg, you can manually specify the keyframe interval which specifies the distance between I-frames.

I can't provide insight as to why the videos render smoothly on Safari and not on Chrome / FF, but creating a video with a smaller keyframe / GOP interval alleviates this issue, at the cost of a larger file size.

Try convert your video with the following:
ffmpeg -i input.mp4 -g 4 -vcodec libx264 -profile:v main -level:v 4.1 -an -movflags faststart output.mp4

The key flag in the above being -g 4 which sets a keyframe every 4 frames.

1
  • Thank you very much, this answer did help. The original question did ask why Safari rewinds the video much smoother, I am interested to know why it is. I tested this on Ubuntu 22.04, and Epiphany 42.1 rewinds the video smoothly while other browsers (Chrome, Firefox, Edge) not. So this is not only about mac specific optimization. Commented Jun 2, 2022 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.