Search code examples
htmlcanvashtml5-canvasemoji

How to load and draw emojis on canvas efficiently?


I would like to print an emoji on html canvas.

It can be done using images, but it is cumbersome. Is there a better way?

const canvas = document.querySelector("#canvas");
const contex = canvas.getContext("2d");

var img = new Image();
img.src = "emoji.jpg";
img.addEventListener(
  "load",
  () => {
    context.drawImage(img, 0, 0, 200, 200);
  }
);
img.src = "img.jpg";
#canvas {
  background: red;
}
<canvas id="canvas"></canvas>

Edit:

Okey, I think my question is misunderstood. I am able to draw emoji as an image on canvas. I don't want to do that. Because I have to screenshot all the emojis and crop them before printing them on canvas, which is cumbersome. I am looking for a more efficient way.


Solution

  • You can use fillText to draw the unicode emoji.

    You can copy and paste the emojis from emojipedia.

    I'm certainly not an expert on this so I don't know if there's big drawbacks to doing it this way, but here are some things to consider regardless.

    1. This might not work on all browsers / operating systems.
    2. The standard emoji will likely look different between browsers/systems unless you use a custom font
    3. You should make sure your js is being read as UTF-8 for this to work. This is standard with HTML5, so you probably don't have to change anything unless it doesn't work for you.

    const canvas = document.querySelector("#canvas");
    const contex = canvas.getContext("2d");
    
    // The size of the emoji is set with the font
    contex.font = '100px serif'
    // use these alignment properties for "better" positioning
    contex.textAlign = "center"; 
    contex.textBaseline = "middle"; 
    // draw the emoji
    contex.fillText('😜😂😍', canvas.width / 2, canvas.height / 2)
    #canvas {
      background: #ccc;
    }
    <canvas id="canvas"></canvas>