Skip to content

Instantly share code, notes, and snippets.

@gapspt
Last active August 14, 2022 20:49
Show Gist options
  • Save gapspt/a6e5e3aa9d14791e74f66dadbf284aec to your computer and use it in GitHub Desktop.
Save gapspt/a6e5e3aa9d14791e74f66dadbf284aec to your computer and use it in GitHub Desktop.
Dinamically add an image as an overlay when pressing a specific sequence of keys on the keyboard. The image will scale with the browser window (responsive) while keeping its original ratio.
function addOverlayImage(url, scale) {
let e = document.createElement('img');
e.style.visibility = 'hidden';
e.src = url;
let w, h, r = 0;
function setSize() {
if (r) {
let winR = window.innerWidth / window.innerHeight;
let s = scale * (r > winR ? window.innerWidth / w : window.innerHeight / h);
e.width = w * s;
e.height = h * s;
}
}
e.onload = function() {
w = e.width;
h = e.height;
r = w / h;
setSize();
e.style.position = 'fixed';
e.style.bottom = 0;
e.style.right = 0;
e.style.zIndex = 1000;
e.style.visibility = 'visible';
};
addEventListener('resize', setSize);
document.body.appendChild(e);
}
function triggerOnKeysPressed(keys, cb) {
keys = String(keys).toLowerCase();
let index = -keys.length;
let match = '';
function listener(e) {
let key = String(e.key).toLowerCase();
if (key.length !== 1) {
match = '';
return;
}
match = (match + key).substr(index);
if (match === keys) {
removeEventListener('keypress', listener);
cb();
}
}
addEventListener('keypress', listener);
}
triggerOnKeysPressed('dog', function() {
addOverlayImage('https://cdna.artstation.com/p/assets/images/images/029/160/910/original/paulette-arochena-follow-4.gif', 0.5);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment