Canvas Video aspect-ratio
by Julien Etienne
HTML
<div class="player">
<div class="wrap">
<video data-dil-wide-aspect-ratio="true"
width="800"
height="450"
><canvas></canvas></video>
</div>
</div>
CSS
.player {
width: 50%;
aspect-ratio: 16/6;
display: flex;
justify-content: center;
align-items: center;
background: lime;
resize: both;
overflow: hidden;
}
.canvas-wrap {
/* width: 100%; */
height: 100%;
background: rgba(0,0,255,0.7);
}
[data-dil-wide-aspect-ratio="true"] {
height: 100%;
width: auto;
}
.wrap {
width: 100%;
height:100%;
display: flex;
justify-content: center;
align-items: center;
}
video {
display: block;
width: 100%;
height: auto;
background: rgba(255,0,0,0.4);
background: transparent;
}
canvas {
width: 100%;
height: 100%;
background: pink;
position: absolute;
z-index: 100;
}
JavaScript
const player = document.querySelector('.player')
const canvas = document.querySelector('video')
var videoWidth = 400;
var videoHeight = 225;
var videoAspectRatio = videoWidth / videoHeight;
player.addEventListener('mousemove', () => {
const {offsetHeight, offsetWidth} = player;
const playerAspectRatio = offsetWidth / offsetHeight;
if(playerAspectRatio < videoAspectRatio) {
canvas.dataset.dilWideAspectRatio = false;
}else {
canvas.dataset.dilWideAspectRatio = true;
}
})