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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With