Skip to content

Instantly share code, notes, and snippets.

@ejb
Last active May 3, 2017 18:18
Show Gist options
  • Save ejb/e56b1ed8e8e9388c0012cedc227f9be9 to your computer and use it in GitHub Desktop.
Save ejb/e56b1ed8e8e9388c0012cedc227f9be9 to your computer and use it in GitHub Desktop.
Fill an element with celebratory (financial) emojis. As seen on http://www.wsj.com/graphics/has-the-dow-hit-20000-yet/
function celebrate(el) {
if (doesSupportEmoji() === false) {
// browser does not support emoji, provide a fallback if you like
return;
}
var can = document.createElement('canvas');
var ctx = can.getContext('2d');
can.width = el.offsetWidth;
can.height = el.offsetHeight;
can.style.position = 'absolute';
can.style.top = 0;
can.style.left = 0;
can.style.zIndex = -10;
el.appendChild(can);
var emojiOnscreen = [];
function newEmoji() {
var emoji = (function() {
var n = Math.random();
if (n < 0.2) {
return 'πŸ˜ƒ';
} else if (n < 0.3) {
return 'πŸ’°';
} else if (n < 0.4) {
return 'πŸ“ˆ'
} else if (n < 0.45) {
return 'πŸ””';
} else if (n < 0.5) {
return '🎈';
} else if (n < 0.55) {
return 'πŸ”₯';
} else if (n < 0.6) {
return 'πŸ’Έ';
}
return 'πŸŽ‰';
}());
return {
emoji: emoji,
x: Math.random() * can.width,
y: (Math.random() + 1) * can.height,
dir: Math.random() < 0.5 ? -1 : 1,
age: 0,
move: function() {
var mx = this.age * this.dir;
var newx = this.x + mx;
var newy = this.y - Math.sin(this.age/80) * 400;
if ((newx > -25) && (newx < can.width + 25)) {
ctx.fillText( this.emoji, newx, newy );
this.age += 1;
}
}
}
}
for (var i=0; i<=30; i++) {
emojiOnscreen.push(newEmoji());
}
setInterval(function() {
emojiOnscreen.push(newEmoji());
}, 100);
update();
function update(){
ctx.fillStyle = '#52a045';
ctx.fillRect(0,0,10000000,10000000);
ctx.fillStyle = 'black';
ctx.font = '25px Arial';
emojiOnscreen.forEach(function(e) {
e.move();
});
window.requestAnimationFrame(update);
}
window.addEventListener('resize',function(){
can.width = el.offsetWidth;
can.height = el.offsetHeight;
});
function doesSupportEmoji() {
var context, smiley;
if (!document.createElement('canvas').getContext) return;
context = document.createElement('canvas').getContext('2d');
if (typeof context.fillText != 'function') return;
smile = String.fromCodePoint(0x1F604); // :smile: String.fromCharCode(55357) + String.fromCharCode(56835)
context.textBaseline = "top";
context.font = "32px Arial";
context.fillText(smile, 0, 0);
return context.getImageData(16, 16, 1, 1).data[0] !== 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment