Cross-platform transparent background videos for the web
Videos are a great addition to web design, but working with transparent background videos can be painful. There's no single format that works cross-platform. Even matching the video background to your page's background color won't work due to devices and browsers using different color profiles. With that being said, here's a quick way to achieve background transparency that works everywhere.
First, the code snippet on your page will look like this:
<video>
<source src="video.mp4" type="video/mp4; codecs=hvc1">
<source src="video.webm" type="video/webm">
</video>
Quick Solution #1: Using Rotato's Alpha Channel Tool
You probably don't need much other than downloading Rotato's Alpha Channel Tool and using it to convert your transparent video to webm and mp4. Don't forget to test your video on multiple browsers and devices. Especially iOS and Android. If Rotato's tool doesn't work for you, keep reading.
Quick Solution #2: Using ffmpeg
There's good support for transparency with webm
, but on iOS and Safari, you will need to create a video with the HEVC (High Efficiency Video Coding) codec. We don't have to get into the details, here's how to do it:
The process consists of 3 steps.
- Extract frames from the video as png files.
- Create video from the png files.
- Optimize the video.
Pre-requisites
We will be using ffmpeg
to perform the first and second steps above. So, if you haven't already, go ahead and install ffmpeg
.
brew install ffmpeg
Extract frames from the video as png files
Open your terminal. Go to the folder where your video is located and run the command below:
ffmpeg -i input_video.mov frame_%d.png
You will get hundreds of .png files.
Create video from the png files
In your terminal, still on the folder with the frame pngs, we will run a couple of commands.
First, let's create the webm
file:
ffmpeg -framerate 36 -f image2 -i frame_%d.png -c:v libvpx-vp9 webm_video.webm
Then create an HEVC mov
file.
ffmpeg -framerate 36 -f image2 -i frame_%d.png -c:v prores_ks -profile:v 4 -vendor apl0 -bits_per_mb 8000 -pix_fmt yuva444p10le mov_video.mov
As you can probably see, the mov_video.mov
file is huge. So here's what we are going to do next.
Open the video in QuickTime Player, then go to File > Export As > 1080p
or choose a different size.
Then select Smaller File Size (HEVC)
, tick Preserve Transparency
and click Save
.
You will get a smaller .mov
file that can be used as follows:
<video>
<source src="video.mov" type="video/mp4; codecs=hvc1">
<source src="video.webm" type="video/webm">
</video>
If you prefer to have a .mp4 file instead of a .mov file, you can use Rotato's converter tool, to turn the .mov file into an .mp4 file.
And that's it, you should now have video files that are compatible across multiple browsers and devices.