So that you need an auto-playing looping video with out sound? In fashionable vernacular that is the very that means of the phrase GIF. The phrase has caught round however the picture format itself is historical and out of date. Twitter, for instance, has a “GIF” button that truly inserts a <video> factor with an MP4 file into your tweet — no .gif in sight. There are a beguiling quantity of the way to realize the identical final result however one factor is obvious: there’s actually no good cause to make use of the cumbersome .gif file format anymore.
Use a HTML <video> factor
It’s simple to recreate the habits of a GIF utilizing the HTML video factor.
<video autoplay loop muted playsinline src=”cats.mp4″></video>
With this code the video will play routinely in a steady loop with no audio. playsinline signifies that cellular browsers will play the video the place it’s on the web page quite than opening in fullscreen.
Whereas the HTML video factor itself has been supported for a few years, the identical can’t be stated for the wide range of video codecs.
Movies are made up of two components: the container and the video codec. (In case your video incorporates audio then it’s made up of three components, the third being the audio codec.) Containers can retailer video, audio, subtitles and meta data. The 2 commonest containers for video on the net are MP4 and WebM. The container is identical because the file kind — if a file ends with a .mp4 extension, meaning it’s utilizing an MP4 container. The file extension doesn’t inform you the codec although. Examples of video codecs generally used on the net embody VP8, VP9, H.264 and HEVC (H.265). On your video to play on-line, the browser must assist each the video container and the codec.
Browser assist for video is a labyrinthine mess, which is a part of the explanation YouTube embeds are ubiquitous, however that doesn’t work for our use case. Let’s have a look at the video codecs which might be value contemplating.
Containers
MP4 was initially launched in 2001. It’s supported by all net browsers and has been for fairly a while.WebM was launched in 2010. It really works in all browsers aside from iOS Safari.
Codecs
The H.264 codec works in all browsers.HEVC/H.265, the successor of H.264, is supported by Safari, Edge, and Chrome (as of model 105).VP9 is the successor to the VP8 codec. VP9 is supported by all of the browsers that assist WebM.The AV1 codec has been supported in Chrome since 2018 and Firefox since 2019. It has not but shipped in Edge or Safari.
An MP4 file utilizing the H.264 codec will work in every single place, nevertheless it doesn’t ship the highest quality or the smallest file measurement.
AV1 doesn’t have cross-browser assist but however, launched in 2018, it’s probably the most trendy codec round. It’s already getting used, at the least for some movies and platforms, by Netflix, YouTube and Vimeo. AV1 is a royalty-free video codec designed particularly for the web. AV1 was created by the Alliance for Open Media (AOM), a bunch based by Google, Mozilla, Cisco, Microsoft, Netflix, Amazon, and Intel. Apple is now additionally a member, so it’s protected to imagine all browsers will assist AV1 ultimately. Edge is “nonetheless evaluating choices to assist AVIF and AV1.”
The lately redesigned web site from growth consultancy Evil Martians is a testomony to the file-size discount that AV1 is able to.
We’re utilizing video recordsdata for shifting backgrounds on https://t.co/5VndxSCEgv.
In AV1 it’s simply 68 KB, much like the picture file. HEVC is 195 KB, and H264 is 512 КB.
It is a good instance how good AV1 is.https://t.co/lqti7vMdDW pic.twitter.com/DaCnKxy6QK
— Sitnik the Developer (@sitnikcode) September 8, 2022
If you wish to use newer video codecs with fallbacks for older browsers, you should use a number of <supply> parts. The order of the supply parts matter. Specify the perfect supply on the high, and the fallback after.
<video autoplay loop muted playsinline>
<supply src=”cats.webm” kind=”video/webm”> <!– preferrred –>
<supply src=”cats.mp4″ kind=”video/mp4″> <!– fallhack –>
</video>
Given the above code, cats.webm shall be used except the browser doesn’t assist that format, through which case the MP4 shall be displayed as an alternative.
What if you wish to embody a number of MP4 recordsdata, however with every utilizing a special codec? When specifying the sort you possibly can embody a codecs parameter. The syntax is horrifically difficult for anyone who isn’t some form of hardcore codec nerd, nevertheless it seems one thing like this:
<video autoplay loop muted playsinline>
<supply src=”cats.mp4″ kind=”video/mp4; codecs=av01.0.05M.08″ >
<supply src=”cats.mp4″ kind=”video/mp4″ >
</video>
Utilizing the above code the browser will choose AV1 if it might probably play that format and fallback to the universally-supported H.264 if not. For AV1, the codecs parameter at all times begins with av01. The following quantity is both 0 (for predominant profile), 1 (for top profile) or 2 (for skilled profile). Subsequent comes a two-digit degree quantity. That is adopted both by the letter M (for predominant tier) or H (for top tier). It’s obscure what any these issues imply, so you could possibly present your AV1 video in a WebM container and keep away from specifying the codec solely.
Most video modifying software program doesn’t permit you to export as AV1, and even as WebM. If you wish to use a kind of codecs you’ll have to export your video as one thing else, like a .mov, after which convert it utilizing the command-line device FFmpeg:
ffmpeg -i yourSourceFile.mov -map_metadata -1 -c:a libopus -c:v librav1e -qp 80 -tile-columns 2 -tile-rows 2 -pix_fmt yuv420p -movflags +faststart -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" videoTitle.mp4
You need to use probably the most high-resolution supply file you possibly can. Clearly, as soon as picture high quality is misplaced you possibly can’t enhance it via conversion to a superior format. Utilizing a .gif as a supply file isn’t preferrred as a result of the visible high quality of .gif isn’t nice, however you’ll nonetheless get the advantage of a big discount in file measurement:
ffmpeg -i cats.gif -map_metadata -1 -an opus -c:v librav1e -qp 80 -tile-columns 2 -tile-rows 2 -pix_fmt yuv420p -movflags +faststart -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" cats.mp4
On Mac, you possibly can obtain FFmpeg utilizing Homebrew:
brew set up ffmpeg
Right here’s a pleasant instance of video in net design on the masterfully designed Oxide web site:
Website serves clear video the place it might probably – WebM on most browsers, clear mov on Safari, which helps you to do some delicate however good hover results pic.twitter.com/wa0eTgGWa2
— Ben Leonard (@lenjaminbeonard) August 19, 2022
If you wish to use the video as a background and place different parts on high of it, working with <video> is barely more difficult than a CSS background-image, and requires code that goes one thing like this:
.video-parent {
place: relative;
width: 100vw;
peak: 100vh;
}
.video-parent video {
object-fit: cowl;
place: absolute;
inset: 0;
z-index: -1;
width: 100%;
peak: 100%;
}
The <video> factor is a superbly okay possibility for changing GIFs nevertheless it does have one unlucky side-effect: it prevents a person’s display screen from going to sleep, as defined in this submit from an ex- product supervisor on the Microsoft Edge browser.
The advantages of utilizing a picture
Whether or not it’s an animated WebP or animated AVIF file, utilizing photographs quite than video comes with some advantages.
I’m unsure how many individuals really need to art-direct their GIFs, however utilizing the <image> factor does open up some prospects that couldn’t simply be achieved with <video>. You may specify totally different animations for mild and darkish mode, for instance:
<image>
<supply srcset=”dark-animation.avifs” media=”(prefers-color-scheme: darkish)”>
<img src=”light-animation.avif” alt=””>
</image>
We would desire a video on cellular to be a special facet ratio than on desktop. We may simply crop components of the picture with CSS, however that looks as if a waste of bytes and considerably haphazard. Utilizing a media question we are able to show a special animated picture file based mostly on the display screen measurement or orientation:
<image>
<supply kind=”picture/avif” srcset=”typeloop-landscape.avifs” media=”(orientation: panorama)””>
<img src=”typeloop-portrait.avif” alt=””>
</image>
All of that is attainable with video — you should use matchMedia to do any media queries in JavaScript and programmatically change the src of a <video> factor:
const mediaQuery = window.matchMedia(“(prefers-color-scheme: darkish)”);
if (mediaQuery.matches) {
doc.querySelector(“video”).src = “dark-animation.mp4”;
}
I imagine that at any time when there’s a strategy to do one thing with markup it needs to be most popular over doing it JavaScript.
You should utilize raster photographs inside an SVG utilizing the <picture> factor. This contains animated picture codecs. There’s not a lot you are able to do with a picture inside an SVG that you just couldn’t already do with CSS, however in the event you group a picture with vector parts inside an SVG, then you definately do get the profit that the totally different parts transfer and scale collectively.
The <img> factor has the advantage of native lazy-loading:
<img loading=”lazy” src=”cats.avif” alt=”cats”>
If you’d like a background video that takes up your entire display screen, it’s barely simpler to place a background-image than a HTML <video> factor:
.background-video {
background-image: url(“coolbackground.webp”);
background-repeat: no-repeat;
background-size: cowl;
peak: 100vh;
width: 100vh;
}
If you wish to assist older browsers you could possibly use the <image> factor with a fallback of both an animated WebP or, only for Safari, an img with a video src, or in the event you care about historical browsers, perhaps an APNG (animated PNG) or a GIF. Utilizing a number of picture codecs this manner could be impractical in the event you’re optimizing photographs manually; however it’s comparatively trivial in the event you’re utilizing a service like Cloudinary.
<image>
<supply kind=”picture/avif” srcset=”cats.avif”>
<img src=”cats.webp”>
</image>
There’s nonetheless no well-supported strategy to specify fallback photographs for CSS backgrounds. image-set is an equal of the <image> factor, [but for background-image. Unfortunately, only Firefox currently supports the type attribute of image-set.
.box {
background-image: image-set(
url(“cats.avif”) type(“image/avif”),
url(“cats.webp”) type(“image/webp”));
}
This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.
Desktop
ChromeFirefoxIEEdgeSafari108*89No105*TP
Mobile / Tablet
Android ChromeAndroid FirefoxAndroidiOS Safari105*104105*16.1
Use animated WebP
The WebP image format was introduced by Google in 2010. WebP, including animated WebP, has broad browser support.
<img src=”nyancat.webp” alt=”A cat flying through space leaving a rainbow trail”>
This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.
Desktop
ChromeFirefoxIEEdgeSafari3265No1816.0
Mobile / Tablet
Android ChromeAndroid FirefoxAndroidiOS Safari1051044.2-4.314.0-14.4
Use animated AVIF
WebP is now twelve years old. The more modern AV1 Image File Format (AVIF), released in 2019, is the best image format for most use cases on the web. Converting a .gif file to AVIF can reduce bytes by over 90%.
<img src=”nyancat.avif” alt=”A cat flying through space leaving a rainbow trail”>
As its name suggests, AVIF is based on the the AV1 video codec. Like WebP, AVIF can be used for both still images and animation. There’s not much difference between an animated AVIF file and an AV1 video in an MP4 container.
You can put a shadow on AVIF animation, e.g.:
filter: drop-shadow(2px 4px 6px black);
AVIF is already supported by Safari, Firefox, Samsung Internet, and Chrome. Firefox only shipped support for still images, not animated AVIF. Safari supports animation as of version 16.1. Unfortunately, because Firefox does support AVIF, just not animated AVIF, it’s impossible to successfully use the <picture> element to display AVIF only to browsers that support animation. Given the following code, Firefox would display the AVIF, but as a static image, rather than showing the animated WebP version:
<picture>
<source srcset=”https://fonts.gstatic.com/s/e/notoemoji/latest/1f4a9/512.avif” type=”image/avif”>
<img src=”https://fonts.gstatic.com/s/e/notoemoji/latest/1f4a9/512.webp” alt=”💩” width=”32″ height=”32″>
</picture>
Tooling for AVIF is still improving. Video editing software does not enable you to export footage as animated AVIF or animated WebP. You’ll need to export it in some other format and then convert it. On the website ezgif.com you can upload a video file or a .gif and convert it to AVIF or WebP. You could also use FFmpeg. Using Cloudinary you can upload a video file or an old .gif and convert it to pretty much any format you want — including animated WebP and animated AVIF. As of time of writing, Squoosh, an image conversion app, doesn’t support animated AVIF.
Adoption remains lacking in design software. When viewing a prototype, Figma will play any animated GIFs included in the design. For AVIF, by contrast, you can’t even import or export a still image.
Use a video with an <img> element
In 2018, Safari 11.1 gave developers the ability to use a video file as the source of the HTML <img> element. This works in Safari:
<img src=”cat.mp4″ alt=”A Siamese cat walking in a circle”>
All the same codecs that Safari supports for <video> are supported by <img>. This means you can use MP4, H.264, and HEVC.
In Safari, video files will also work anyplace in CSS where you could use an image, like background-image or border-image:
.video-border {
border: 40px solid transparent;
border-image: url(abstract_bg_animation.mp4) 100 round;
}
One strange consequence of this feature in Safari is that the poster image of a <video> element can also be a video. The poster will autoplay even if you have blocked video’s from auto-playing. Safari claimed this feature came with performance benefits, not just over using .gif files but also over using the <video> element. According to Apple:
By placing your videos in <img> elements, the content loads faster, uses less battery power, and gets better performance.
Colin Bendell, co-author of O‘Reilly’s High Performance Images, wrote about the shortcomings of the <video> tag for our use case:
Unlike <img> tags, browsers do not preload <video> content. Generally preloaders only preload JavaScript, CSS, and image resources because they are critical for the page layout. Since <video> content can be any length – from micro-form to long-form – <video> tags are skipped until the main thread is ready to parse its content. This delays the loading of <video> content by many hundreds of milliseconds.
[…]Worse but, many browsers assume that <video> tags include long-form content material. As a substitute of downloading the entire video file directly, which might waste your cell knowledge plan in instances the place you don’t find yourself watching the entire video, the browser will first carry out a 1-byte request to check if the server helps HTTP Vary Requests. Then it should comply with with a number of vary requests in varied chunk sizes to make sure that the video is satisfactorily (however not over-) buffered. The consequence is a number of TCP spherical journeys earlier than the browser may even begin to decode the content material and important delays earlier than the person sees something. On high-latency mobile connections, these spherical journeys can set video masses again by tons of or 1000’s of milliseconds.
Chrome has marked this as “WontFix” — that means they don’t intend to ever assist this characteristic, for varied causes. There’s, nonetheless, an open challenge on GitHub so as to add it to the HTML spec, which might pressure Google’s hand.
Respecting person preferences
Video has the advantage of routinely respecting a customers preferences. Firefox and Safari permit customers to block movies from routinely enjoying, even when they don’t have any audio. Listed below are the settings in Firefox, for instance:
The person can nonetheless resolve to observe a sure video by right-clicking and urgent play within the menu, or allow autoplay for all movies on a selected web site.
For customers who haven’t disabled autoplay, it’s good to have the choice to pause an animation in the event you occur to seek out it annoying or distracting (a person can nonetheless right-click to convey up the pause possibility in a menu when video controls aren’t proven). Success Criterion 2.2.2 Pause, Cease, Disguise of the WCAG accessibility tips states:
For any shifting, blinking or scrolling data that (1) begins routinely, (2) lasts greater than 5 seconds, and (3) is introduced in parallel with different content material, there’s a mechanism for the person to pause, cease, or cover it except the motion, blinking, or scrolling is a part of an exercise the place it’s important.
With the <video> factor, you’ll obtain that criterion with none extra growth.
There’s additionally a “scale back movement” person setting that builders can respect by lowering or eradicating CSS and JavaScript net animations.
It’s also possible to use it to show a nonetheless picture as an alternative of an animation. This takes further code to implement — and you could host a nonetheless picture in extra to your animated picture.
<image>
<supply
srcset=”nyancat.avifs”
kind=”picture/avif”
media=”(prefers-reduced-motion: no-preference)”
/>
<img src=”nyancat.png” alt=”Nyan cat” width=”250″ peak=”250″ />
</image>
There’s one other draw back. When utilizing the <image> factor on this manner if the person has checked “scale back movement”there’s no manner for them to see the animation. Simply because a person prefers much less animation, doesn’t imply they by no means need any — they may nonetheless need to have the ability to opt-in and watch one now and again. Not like the <video> factor, displaying a nonetheless picture takes away that alternative.
Checking for progressive enhancement
If you wish to examine that your <image> code is correctly working and fallback photographs are being displayed, you should use the Rendering tab in Chrome DevTools to show off assist for AVIF and WebP picture codecs. Seeing as all browsers now assist WebP, this can be a fairly useful characteristic.
Whereas it’s normally the most suitable choice to create animations with CSS, JavaScript, DOM parts, canvas and SVG, as new picture and video codecs supply smaller recordsdata than what was beforehand attainable, they turn into a helpful possibility for UI animation (quite than simply nyancat loops). For one-off animations, an AVIF file might be going to be extra performant than importing a complete animation library.
Right here’s a enjoyable instance of utilizing video for UI from all the best way again in 2017 for the League of Legends web site.
Lottie
After Results is a well-liked animation device from Adobe. Utilizing an extension referred to as Bodymovin, you possibly can export animation knowledge from After Results as a JSON file.
Then there’s Lottie, an open-source animation library from Airbnb that may take that JSON file and render it as an animation on totally different platforms. The library is obtainable for native iOS, Android, and React Native purposes, in addition to for the online. You possibly can see examples from Google Residence, Goal, and Walgreens, amongst others.
When you’ve included the dependency you could write a small quantity of JavaScript code to get the animation to run:
<div id=”lottie”></div>
const animation = bodymovin.loadAnimation({
container: doc.getElementById(‘lottie’),
path: ‘myAnimation.json’,
renderer: ‘svg’,
loop: true,
autoplay: true,
})
You possibly can optionally change these settings to solely play after an occasion:
const lottieContainer = doc.getElementById(‘lottie’);
const animation = bodymovin.loadAnimation({
container: lottieContainer,
path: ‘myAnimation.json’,
renderer: ‘svg’,
loop: true,
autoplay: false,
})
// Play the animation on hover
lottieContainer.addEventListener(‘mouseover’, () => {
animation.play();
});
// Cease the animation after enjoying as soon as
animation.addEventListener(‘loopComplete’, perform() {
animation.cease();
});
Right here’s a cute instance of a cat typing on a keyboard I took from Lottiefiles.com (the web site is a helpful web site for previewing your personal Lottie JSON file animations, quite than needing to put in After Results, as properly discovering animations from different creatives):
It’s also possible to programmatically play an animation backwards and alter the playback price.
When you do select to make use of Lottie, there’s a Figma plugin for Lottie however all it does is convert JSON recordsdata to .gif in order that they are often previewed in prototyping mode.
Abd what about Lottie’s efficiency? There’s measurement of the library — 254.6KB (63.8 gzipped) — and the dimensions of the JSON file to contemplate. There’s additionally the quantity of DOM parts that get created for the SVG components. When you run into this challenge, Lottie has the choice to render to a HTML <canvas>, however you’ll want to make use of a special model of the JavaScript library.
const animation = bodymovin.loadAnimation({
container: doc.getElementById(‘lottie’),
path: ‘myAnimation.json’,
renderer: ‘canvas’,
})
Lottie isn’t a full alternative for gifs. Whereas After Results itself is usually used with video clips, and Lottie can render to a HTML <canvas>, and a canvas can play video clips, you wouldn’t use a Lottie file for that goal. Lottie is for superior 2D animations, not a lot for video. There are different instruments for creating advanced net animations with a GUI like SVGator and Rive, however I haven’t tried them myself. 🤷♂️
I want there was a TL;DR for this text. For now, at the least, there’s no clear winner…
GIFs With out the .gif: The Most Performant Picture and Video Choices Proper Now initially revealed on CSS-Tips, which is a part of the DigitalOcean household. You need to get the e-newsletter.
Subscribe to MarketingSolution.
Receive web development discounts & web design tutorials.
Now! Lets GROW Together!