Search code examples
javascriptunicodespriteemoji

How to convert an emoji image to Unicode in JavaScript, or reflect a custom emoji for a given Unicode?


I'm trying to understand how to implement custom emojis for user input and I can't seem to get a handle on it.

I see that sites like Facebook initially show a list of small .png emoji images, then, once you click the image, it converts it to a Unicode character.

Also, I've been digging through custom emoji packages that use sprite images.

I can't find any material that explains how to utilize a sprite, or a single image, then convert this to Unicode on the fly to be displayed later.

If you can't convert images to Unicode on the fly, how is it that different sites reflect their own custom version of an emoji with a given Unicode character?


Solution

  • Broadly speaking, there are two methods for adding emoji functionality to user inputs:

    1. Unicode characters, which relies on a custom font imported by the developer OR the browser vendors default font, to determine which version of a particular emoji is used. You simply type in the unicode string and the browser inserts a given emoji based on the font. Check out unicode emojis here. and also this post explains more about unicode usage for emojis.
    2. The insertion of images into a rich text editor (RTE). This technique relies on having single emoji images (typically .png) or sprite sheets that the developer can use with the RTE. This article is a great place to start.
    • The first method can be harder to customize the emoji unless you're into making custom fonts. RTE plugins like TinyMCE are a simple and quick way to tinker with unicode emojis.

    • The second method becomes a bit more complex, and is used by some of the big players like Facebook and Twitter. As with most things coding, with complexity comes flexibility. This method involves programmatically transposing some plain-text flag such as :smile: into an html element like <img src='smile.png' />. It creates a text area by utilizing the contenteditable div tag. Inside this div, the content is edited programmatically in order to add or remove emoji images, bold/italic letters, etc...

    In order to better understand how the second method works, I created react-ez-emoji, which is a lightweight, emoji-enabled contenteditable div that allows you to use any emoji image file you'd like. It would be a good start for anyone looking to study the topic, but I don't recommend it for production.

    This article does a good job explaining the limitations of Unicode emojis, and why the second option is more customizable and efficient.