Skip to content

Instantly share code, notes, and snippets.

@arpruss
Last active July 11, 2023 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save arpruss/74abc1bc95ae08e543b9b74f15a23b07 to your computer and use it in GitHub Desktop.
Save arpruss/74abc1bc95ae08e543b9b74f15a23b07 to your computer and use it in GitHub Desktop.
Bookmarklet to change aspect ratio of html5 video
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 = prompt("Enter one of these:\n"+
"(a) horizontal,vertical : a pair of scale ratios\n"+
"(b) horizontal:vertical : the correct aspect ratio for a badly encoded video\n", "1,1");
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