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
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
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;
}
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