Skip to content

Instantly share code, notes, and snippets.

@sergiks
Created August 7, 2018 21:11
Show Gist options
  • Save sergiks/0bd2ec1cdd81033c81f7b85abb1d0612 to your computer and use it in GitHub Desktop.
Save sergiks/0bd2ec1cdd81033c81f7b85abb1d0612 to your computer and use it in GitHub Desktop.
Scale video to fit window and an overlay to fit video
/**
* algorithm to center fit overlay image
* over an arbitrary sized video or image
*/
function fit(video_width, video_height) {
const video_aspect = video_width / video_height;
// Overlay image - png with transparency
const over_width = 1280;
const over_height = 720;
const over_aspect = over_width / over_height;
// Container to display preview
const window_width = 600;
const window_height = 420;
const window_aspect = window_width / window_height;
let video_k;
// Fit video to container
if( window_aspect < video_aspect) {
// common top+bottom, equal heights
video_k = window_height / video_height;
} else {
// common sides, equal width
video_k = window_width / video_width;
}
// Video scale to display within the window
const new_video_height = video_height * video_k;
const new_video_width = video_width * video_k;
// Video positioning within display window
const video_x = (window_width - new_video_width) / 2;
const video_y = (window_height - new_video_height) / 2;
// TODO: scale and place video
let over_k;
// Overlay scale to place on top of scaled video
if( over_aspect < video_aspect) {
// equal heights
over_k = video_height / over_height;
} else {
// equal widths
over_k = video_width / over_width;
}
// Scale overlay to fit displayed video
const new_over_width = over_width * over_k;
const new_over_height = over_height * over_k;
// Position overlay centered with the video
const over_x = video_x + (new_video_width - new_over_width) / 2;
const over_y = video_y + (new_video_height - new_over_height) / 2
// TODO: scale and place overlay.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment