const canvas = document.querySelector('canvas');
canvas.width = 30;
canvas.height = 30;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#121212'; // 12 => 17 in decimal
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = "20px Arial";
ctx.fillText("?", 0, 20);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// an array in the format [r, g, b, count] decimal
const sums = imageData.data.reduce((r, v, i) => {
if (v === 18) return r; // our fill color, skip
if (i % 4 !== 3) { // i % 4 === 3 is transparent, ignoring
r[i % 4] += v;
r[3]++;
}
return r;
}, [0, 0, 0, 0]);
sums[3] = sums[3] / 3; // divide by 3 since we counted each pixel 3 times
const averages = [Math.floor(sums[0] / sums[3]), Math.floor(sums[1] / sums[3]), Math.floor(sums[2] / sums[3])];
// just to see the color
ctx.fillStyle = `rgb(${averages.join(',')})`;
ctx.fillRect(0, 0, canvas.width, canvas.height);
canvas {
border: 1px solid #000;
}
.emoji {
text-shadow: rgba(0, 0, 0, .5) 2px 2px 2px;
}
<div class="emoji">?</div>
<canvas></canvas>