Skip to content

Instantly share code, notes, and snippets.

@rattrayalex
Last active November 17, 2020 02:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rattrayalex/7ec25b748dd29ea4a96d8127e77dc33c to your computer and use it in GitHub Desktop.
Save rattrayalex/7ec25b748dd29ea4a96d8127e77dc33c to your computer and use it in GitHub Desktop.
Fall back to twitter's twemoji emoji when there is inadequate native emoji support (eg; on Windows)
<html>
<body>
<div class="has-emoji">Hello world! I'm a unicorn: 🦄</div>
<script>
// Stolen from Modernizr: https://github.com/Modernizr/Modernizr/blob/v3.5.0/feature-detects/emoji.js
const hasEmojiSupport = () => {
var pixelRatio = window.devicePixelRatio || 1;
var offset = 12 * pixelRatio;
var node = document.createElement('canvas');
var ctx = node.getContext('2d');
ctx.fillStyle = '#f00';
ctx.textBaseline = 'top';
ctx.font = '32px Arial'; // Replace with the fonts you use, if they have better emoji support
ctx.fillText('🦄', 0, 0); // Replace with an emoji whose support you care about
return ctx.getImageData(offset, offset, 1, 1).data[0] !== 0;
}
if (!hasEmojiSupport()) {
console.log('emoji unsupported');
// Inserts https://twemoji.twitter.com/
const twemojiEl = document.createElement("script");
twemojiEl.src = "https://twemoji.maxcdn.com/v/13.0.1/twemoji.min.js";
twemojiEl.onload = () => {
document.querySelectorAll('.has-emoji').forEach(el => { // Replace with selectors you care about.
twemoji.parse(el);
});
}
document.body.appendChild(twemojiEl);
} else {
console.log('emoji supported')
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment