Video Aspect Ratio Crop
by Tim Noetzel
HTML
<div class="demo">
<div>
<button onClick="switchAspectRatio('16x9')">
16x9
</button>
<button onClick="switchAspectRatio('4x3')">
4x3
</button>
</div>
<div class="crop-container aspect-ratio-16x9">
<video id="the-video" autoplay>
<source src="https://vid.ly/5u4h3e?content=video" type="video/mp4">
</video>
</div>
</div>
CSS
.demo {
width: 50vw;
}
.crop-container{
overflow:hidden;
display:flex;
align-items: center;
justify-content: center;
height: 0;
position: relative;
}
/* Center the video in the crop box */
.crop-container video {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 100%;
}
.aspect-ratio-16x9 {
padding-top: calc(9 / 16 * 100%);
}
.aspect-ratio-4x3 {
padding-top: calc(3 / 4 * 100%);
}
JavaScript
function switchAspectRatio(ratio) {
console.log("YO");
const el = document.querySelector('.crop-container');
// Remove any previous aspect ratios
for (let i = el.classList.length - 1; i >= 0; i--) {
const className = el.classList[i];
if (className.startsWith('aspect-ratio-')) {
el.classList.remove(className);
}
}
// Add the new one
el.classList.add(`aspect-ratio-${ratio}`);
}