How can I detect rendering support for emoji in JavaScript?

牧云@^-^@ 提交于 2019-11-28 01:17:23

问题


I want to add emoji to my site, but hide them if they're not supported on the platform, rather than showing little squares.

I have a feeling that this isn't possible, but does anybody disagree? How can this be done?

C


回答1:


Try to paint a font (in the Emoji range) to canvas and read a pixel using getImageData. If the pixel's Alpha channel data[3] you're interested-in is not transparent (like for example in the center of ) than might be an Emoji 😗

function supportsEmoji () {
  var ctx = document.createElement("canvas").getContext("2d");
  ctx.fillText("😗", -2, 4);
  return ctx.getImageData(0, 0, 1, 1).data[3] > 0; // Not a transparent pixel
}

console.log( supportsEmoji() );

or something like that...

Tested the above in Chrome, Firefox, IE11, Edge, Safari
Safari returns false and IE11 although has Emoji but without colors returned true.


Edit:
Amy kindly noted in the comments section that Modernizr has detection for Emoji - so you might give it also a go


回答2:


The flag emoji are a bit of an edge case to the answers posted here. Since if the flag emoji is not supported on a device, a fallback of the country code is rendered instead. E.g. the union jack flag (🇬🇧) will become -> GB.

Windows 10 doesn't support the Emoji Flags.

This script uses a similar method to the existing answer, but instead checks to see if the canvas is greyscale. If there are colours in the canvas, we know an emoji was rendered.

 function supportsFlagEmoji () {
    var canvas = document.createElement("canvas");
    canvas.height = 10;
    canvas.width = canvas.height*2;
    var ctx = canvas.getContext("2d");
    ctx.font = canvas.height+"px Arial";
    ctx.fillText("🇬🇧", 0, canvas.height);
    var data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
    var i = 0;
    while(i<data.length) {
        if (data[i] !== data[i+1] || data[i] !== data[i+2]) return true;
        i+=4;
    }
    return false;
}



回答3:


In case if someone is looking for a library, then here is the one if-emoji. It uses the same approach Roko has used in his answer.



来源:https://stackoverflow.com/questions/45576748/how-can-i-detect-rendering-support-for-emoji-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!