Saturday, April 27, 2024
HomeProgrammingGIFs With out the .gif: The Most Performant Picture and Video Choices...

GIFs With out the .gif: The Most Performant Picture and Video Choices Proper Now | CSS-Tips


So that you need an auto-playing looping video with out sound? In widespread vernacular that is the very which means of the phrase GIF. The phrase has caught round however the picture format itself is historic and out of date. Twitter, for instance, has a “GIF” button that really inserts a <video> ingredient with an MP4 file into your tweet — no .gif in sight. There are a beguiling quantity of how to realize the identical final result however one factor is obvious: there’s actually no good purpose to make use of the cumbersome .gif file format anymore.

Use a HTML <video> ingredient

It’s straightforward to recreate the habits of a GIF utilizing the HTML video ingredient.

<video autoplay loop muted playsinline src="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/cats.mp4"></video>

With this code the video will play routinely in a steady loop with no audio. playsinline implies that cell browsers will play the video the place it’s on the web page quite than opening in fullscreen.

Whereas the HTML video ingredient itself has been supported for a few years, the identical can’t be mentioned for the big variety of video codecs.

Movies are made up of two elements: the container and the video codec. (In case your video comprises audio then it’s made up of three elements, the third being the audio codec.) Containers can retailer video, audio, subtitles and meta data. The 2 most typical containers for video on the internet are MP4 and WebM. The container is similar because the file sort — if a file ends with a .mp4 extension, which means it’s utilizing an MP4 container. The file extension doesn’t let you know the codec although. Examples of video codecs generally used on the internet embrace VP8, VP9, H.264 and HEVC (H.265). To 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 rationale YouTube embeds are ubiquitous, however that doesn’t work for our use case. Let’s have a look at the video codecs which can be value contemplating.

Containers

  • MP4 was initially launched in 2001. It’s supported by all internet browsers and has been for fairly a while.
  • WebM was launched in 2010. It really works in all browsers apart 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 all over the place, however 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 fashionable 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 just lately redesigned web site from improvement consultancy Evil Martians is a testomony to the file-size discount that AV1 is able to.

If you wish to use newer video codecs with fallbacks for older browsers, you need to use a number of <supply> components. The order of the supply components matter. Specify the best supply on the prime, and the fallback after.

<video autoplay loop muted playsinline>
  <supply src="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/cats.webm" sort="video/webm"> <!-- excellent -->
  <supply src="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/cats.mp4" sort="video/mp4"> <!-- fallhack -->
</video>

Given the above code, cats.webm might be used except the browser doesn’t assist that format, through which case the MP4 might be displayed as an alternative.

What if you wish to embrace a number of MP4 information, however with every utilizing a distinct codec? When specifying the sort you possibly can embrace a codecs parameter. The syntax is horrifically difficult for anyone who isn’t some form of hardcore codec nerd, however it seems to be one thing like this:

<video autoplay loop muted playsinline>
  <supply src="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/cats.mp4" sort="video/mp4; codecs=av01.0.05M.08" >
  <supply src="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/cats.mp4" sort="video/mp4" >
</video>

Utilizing the above code the browser will choose AV1 if it might 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 stage 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 possibly can present your AV1 video in a WebM container and keep away from specifying the codec fully.

Most video modifying software program doesn’t let you export as AV1, and even as WebM. If you wish to use a kind of codecs you’ll must export your video as one thing else, like a .mov, after which convert it utilizing the command-line software 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 &quot;scale=trunc(iw/2)*2:trunc(ih/2)*2&quot; 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 excellent 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 &quot;scale=trunc(iw/2)*2:trunc(ih/2)*2&quot; cats.mp4

On Mac, you possibly can obtain FFmpeg utilizing Homebrew:

brew set up ffmpeg

Right here’s a pleasant instance of video in internet design on the masterfully designed Oxide web site:

If you wish to use the video as a background and place different components on prime of it, working with <video> is barely tougher than a CSS background-image, and requires code that goes one thing like this:

.video-parent {
  place: relative;
  width: 100vw;
  top: 100vh;
} 

.video-parent video {
  object-fit: cowl;
  place: absolute;
  inset: 0;
  z-index: -1;
  width: 100%;
  top: 100%;
}

The <video> ingredient is a superbly okay possibility for changing GIFs however it does have one unlucky side-effect: it prevents a person’s display from going to sleep, as defined in this put up 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 photos quite than video comes with some advantages.

I’m unsure how many individuals really wish to art-direct their GIFs, however utilizing the <image> ingredient does open up some potentialities that couldn’t simply be achieved with <video>. You can specify completely different animations for gentle and darkish mode, for instance:

<image>
  <supply srcset="https://css-tricks.com/dark-animation.avifs" media="(prefers-color-scheme: darkish)">
  <img src="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/light-animation.avif" alt="">
</image>

We’d need a video on cell to be a distinct facet ratio than on desktop. We might simply crop elements of the picture with CSS, however that looks as if a waste of bytes and considerably haphazard. Utilizing a media question we will show a distinct animated picture file based mostly on the display measurement or orientation:

<image>
  <supply sort="picture/avif" srcset="https://css-tricks.com/typeloop-landscape.avifs" media="(orientation: panorama)"">
  <img src="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/typeloop-portrait.avif" alt="">
</image>

All of that is attainable with video — you need to use matchMedia to do any media queries in JavaScript and programmatically change the src of a <video> ingredient:

const mediaQuery = window.matchMedia("(prefers-color-scheme: darkish)");
if (mediaQuery.matches) {
  doc.querySelector("video").src = "https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/dark-animation.mp4";
}

I imagine that every time there’s a method to do one thing with markup it needs to be most well-liked over doing it JavaScript.

You should utilize raster photos within an SVG utilizing the <picture> ingredient. This consists of 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 case you group a picture with vector components inside an SVG, you then do get the profit that the completely different components transfer and scale collectively.

The <img> ingredient has the advantage of native lazy-loading:

<img loading="lazy" src="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/cats.avif" alt="cats">

If you would like a background video that takes up the whole display, it’s barely simpler to place a background-image than a HTML <video> ingredient:

.background-video {
  background-image: url("coolbackground.webp");
  background-repeat: no-repeat;
  background-size: cowl;
  top: 100vh;
  width: 100vh;
} 

If you wish to assist older browsers you possibly can use the <image> ingredient with a fallback of both an animated WebP or, only for Safari, an img with a video src, or in case you care about historic browsers, possibly an APNG (animated PNG) or a GIF. Utilizing a number of picture codecs this manner is perhaps impractical in case you’re optimizing photos manually; however it’s comparatively trivial in case you’re utilizing a service like Cloudinary.

<image>
  <supply sort="picture/avif" srcset="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/cats.avif">
  <img src="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/cats.webp">
</image>

There’s nonetheless no well-supported method to specify fallback photos for CSS backgrounds. image-set is an equal of the <image> ingredient, [but for background-image. Unfortunately, only Firefox currently supports the type attribute of image-set.

.box {
  background-image: image-set(
    url("https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/cats.avif") type("image/avif"),
    url("https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/cats.webp") type("image/webp"));
}

Desktop

Chrome Firefox IE Edge Safari
108* 89 No 105* TP

Mobile / Tablet

Android Chrome Android Firefox Android iOS Safari
105* 104 105* 16.1

Use animated WebP

The WebP image format was introduced by Google in 2010. WebP, including animated WebP, has broad browser support.

A cat flying through space leaving a rainbow trail
<img src="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/nyancat.webp" alt="A cat flying through space leaving a rainbow trail">

Desktop

Chrome Firefox IE Edge Safari
32 65 No 18 16.0

Mobile / Tablet

Android Chrome Android Firefox Android iOS Safari
105 104 4.2-4.3 14.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="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/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.

An error in Figma that says files failed to import.

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="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/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 comprise 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 would observe with a number of vary requests in numerous 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 hundreds again by a whole lot or hundreds of milliseconds.

Chrome has marked this as “WontFix” — which means they don’t intend to ever assist this function, for numerous causes. There may be, nevertheless, an open situation on GitHub so as to add it to the HTML spec, which might power Google’s hand.

Respecting person preferences

Video has the advantage of routinely respecting a customers preferences. Firefox and Safari enable customers to block movies from routinely taking part in, even when they don’t have any audio. Listed here are the settings in Firefox, for instance:

firefox autoplay settings open in a modal.

The person can nonetheless determine to look at a sure video by right-clicking and urgent play within the menu, or allow autoplay for all movies on a selected web site.

Contextual menu for a video.

For customers who haven’t disabled autoplay, it’s good to have the choice to pause an animation in case you occur to search out it annoying or distracting (a person can nonetheless right-click to deliver up the pause possibility in a menu when video controls aren’t proven). Success Criterion 2.2.2 Pause, Cease, Cover 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 disguise it except the motion, blinking, or scrolling is a part of an exercise the place it’s important.

With the <video> ingredient, you’ll obtain that criterion with none further improvement.

There’s additionally a “scale back movement” person setting that builders can respect by decreasing or eradicating CSS and JavaScript internet animations.

macOS settings window for display accessibility with rediced motion checked.

You too can use it to show a nonetheless picture as an alternative of an animation. This takes additional code to implement — and it is advisable host a nonetheless picture in further to your animated picture.

<image>
  <supply
    srcset="https://css-tricks.com/nyancat.avifs"
    sort="picture/avif"
    media="(prefers-reduced-motion: no-preference)"
  />
  <img src="https://css-tricks.com/gifs-without-the-gif-the-most-performant-image-and-video-options-right-now/nyancat.png" alt="Nyan cat" width="250" top="250" />
</image>

There’s one other draw back. When utilizing the <image> ingredient on this method if the person has checked “scale back movement”there’s no method 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 every so often. Not like the <video> ingredient, displaying a nonetheless picture takes away that alternative.

Checking for progressive enhancement

If you wish to test that your <image> code is correctly working and fallback photos are being displayed, you need to use the Rendering tab in Chrome DevTools to show off assist for AVIF and WebP picture codecs. Seeing as all browsers now assist WebP, it is a fairly helpful function.

Chrome DevTools with Rendering panel open optons for disabling AVIF and WebP images.

Whereas it’s normally the best choice to create animations with CSS, JavaScript, DOM components, canvas and SVG, as new picture and video codecs provide smaller information than what was beforehand attainable, they grow to be 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.

Circular badge that reads Match Accepted with an animated blue progress highlight going around it.
Right here’s a enjoyable instance of utilizing video for UI from all the way in which again in 2017 for the League of Legends web site.

Lottie

After Results is a well-liked animation software from Adobe. Utilizing an extension known 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 completely different platforms. The library is obtainable for native iOS, Android, and React Native purposes, in addition to for the online. You may see examples from Google Residence, Goal, and Walgreens, amongst others.

When you’ve included the dependency it is advisable 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 may 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 taking part in 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):

You too can programmatically play an animation backwards and alter the playback price.

In case you do select to make use of Lottie, there’s a Figma plugin for Lottie however all it does is convert JSON information 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 scale of the JSON file to contemplate. There’s additionally the quantity of DOM components that get created for the SVG elements. In case you run into this situation, Lottie has the choice to render to a HTML <canvas>, however you’ll want to make use of a distinct 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 commonly 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 function. Lottie is for superior 2D animations, not a lot for video. There are different instruments for creating complicated internet 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…



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments