Skip to content

Instantly share code, notes, and snippets.

@seanf
Forked from arpruss/stretchvideo.js
Last active May 10, 2020 09:42
Show Gist options
  • Save seanf/fef460ec4966d4784357dd02f3921ef3 to your computer and use it in GitHub Desktop.
Save seanf/fef460ec4966d4784357dd02f3921ef3 to your computer and use it in GitHub Desktop.
Bookmarklet to change aspect ratio of html5 video to 4:3
document.dispatchEvent(new Event('mobi.omegacentauri.killStretchVideoEvent'));
var vid = document.getElementsByTagName('video');
if (vid.length == 0) {
alert("No video elements found in this page.");
}
else {
var mode = "4:3";
var stretchX = null;
var stretchY = null;
var ratio = null;
if (mode != null) {
var colon = mode.indexOf(":");
if (colon >= 0) {
ratio = parseFloat(mode.substring(0,colon).trim()) / parseFloat(mode.substring(colon+1).trim());
}
else {
var comma = mode.indexOf(",");
if (comma < 0) {
stretchX = parseFloat(mode);
stretchY = 1;
}
else {
stretchX = parseFloat(mode.substring(0,comma).trim());
stretchY = parseFloat(mode.substring(comma+1).trim());
}
}
function stretchVideo(v) {
if (v.style.background != "black")
v.style.background = "black";
var transform = null;
if (stretchX != null) {
transform = "scale("+stretchX+","+stretchY+")";
}
else if (ratio > 0) {
if (v.style.objectFit != "contain")
v.style.objectFit = "contain";
videoRatio = v.videoWidth / v.videoHeight;
if (videoRatio >= ratio) {
transform = "scaleX("+(ratio/videoRatio)+")";
}
else {
transform = "scaleY("+(videoRatio/ratio)+")";
}
}
if (transform != null && v.style.webkitTransform != transform)
v.style.webkitTransform=transform;
}
function stretchAll() {
var vid = document.getElementsByTagName('video');
for(var i=0;i<vid.length;i++)
stretchVideo(vid[i]);
}
stretchAll();
function resizeListener() {
setTimeout(stretchAll, 1000);
}
if (typeof(ResizeObserver) != "undefined") {
var observer = new ResizeObserver(function(entries) {
for (let e of entries) {
setTimeout(function() { stretchVideo(e.target) }, 1000);
}
});
for (var i=0;i<vid.length;i++)
observer.observe(vid[i]);
}
else {
observer = null;
}
function killListener() {
document.removeEventListener('mobi.omegacentauri.killStretchVideoEvent', killListener);
window.removeEventListener('resize', resizeListener);
if (observer != null)
for(var i=0;i<vid.length;i++)
observer.unobserve(vid[i]);
}
document.addEventListener('mobi.omegacentauri.killStretchVideoEvent', killListener);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment