Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created July 19, 2014 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/1c3b75c82be89b411420 to your computer and use it in GitHub Desktop.
Save jonathantneal/1c3b75c82be89b411420 to your computer and use it in GitHub Desktop.
ScaleJS
<!doctype html>
<title>scale</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<style>
body { margin: 10em auto; max-width: 640px; }
#image { display: block; height: 0; overflow: hidden; padding-bottom: 75%; position: relative; }
#image { background-color: #999; border-radius: 5px; box-shadow: 0 0 0 10px #777; }
#image > * { display: block; height: 100%; left: 0; position: absolute; top: 0; width: 100%; }
</style>
<h1>scale</h1>
<div id="image" data-src="scale.m4v" data-size="contain" data-scale="1"></div>
<script>
var LISTENER = 'addEventListener' in this ? ['addEventListener', ''] : ['attachEvent', 'on'];
function getScale(frame) {
function onload() {
var
mediaWidth = (media.videoWidth || media.naturalWidth || media.width),
mediaHeight = (media.videoHeight || media.naturalHeight || media.height),
frameHeight = frame.offsetHeight,
frameWidth = frame.offsetWidth,
frameRatio = frameHeight / frameWidth,
mediaRatio = mediaHeight / mediaWidth,
ratioSwitch = size === 'cover' ? frameRatio > mediaRatio : mediaRatio > frameRatio,
height = ratioSwitch ? frameHeight : mediaHeight * frameWidth / mediaWidth,
width = ratioSwitch ? mediaWidth * frameHeight / mediaHeight : frameWidth,
left = -(width * scale - frameWidth) / 2,
top = -(height * scale - frameHeight) / 2;
style.height = height / frameHeight * 100 * scale + '%';
style.left = left / frameWidth * 100 + '%';
style.top = top / frameHeight * 100 + '%';
style.width = width / frameWidth * 100 * scale + '%';
frame.appendChild(media);
}
var
src = frame.getAttribute('data-src'),
size = frame.getAttribute('data-size') || 'cover',
scale = parseFloat(frame.getAttribute('data-scale')) || 1,
type = frame.getAttribute('data-type') || /\.(3g\d?p?|avi|f4p?v?|h\d+|mp?e?g?\d?v?|ogv|qt|ts|webm|wmv)\b/.test(src) ? 'video' : 'image',
media = frame.appendChild(document.createElement(type)),
style = media.style;
media.src = src;
if (type === 'video') {
media.loop = true;
media.play();
}
if (media.complete || media.readyState === 4) {
onload();
} else {
media.addEventListener('loadedmetadata', onload);
media.addEventListener('load', onload);
}
}
getScale(document.getElementById('image'));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment