Skip to content

Instantly share code, notes, and snippets.

@davidkelley
Created October 9, 2019 13:36
Show Gist options
  • Save davidkelley/ac0b4f2e8d893b24e0f7db38de5e8895 to your computer and use it in GitHub Desktop.
Save davidkelley/ac0b4f2e8d893b24e0f7db38de5e8895 to your computer and use it in GitHub Desktop.
import React, { useEffect, useRef } from 'react';
const drawBox = (canvas, { background } = {}) => new Promise((resolve, reject) => {
const { width, height } = canvas;
const ctx = canvas.getContext('2d');
if (!ctx) {
return null;
}
const drawBadge = () => {
ctx.font = `${height * 0.6}px sans-serif`;
ctx.textAlign = 'right';
ctx.textBaseline = 'end';
ctx.fillText('✅', width, height - (height * 0.1));
};
if (background) {
const img = new Image();
img.width = width;
img.height = height;
img.addEventListener('load', () => {
ctx.drawImage(img, 0, 0, width, height);
drawBadge();
resolve(canvas.toDataURL('image/png'));
});
img.src = background;
return true;
}
reject(new Error('No background specified'));
});
export default ({ width = 64, height = 64, count = 0 }) => {
let isMounted = true;
const favicon = window.document.querySelector('link[rel="icon"]');
if (!favicon) {
console.warn('⚠️ Tried to render <Favicon/> without a <link ... /> element.');
isMounted = false;
return null;
}
const { href: original } = favicon;
const canvas = useRef();
const handleRender = async () => {
favicon.href = await drawBox(canvas.current, {
background: original,
});
};
useEffect(() => {
handleRender();
return () => {
isMounted = false;
};
});
return (
<>
<canvas hidden width={width} height={height} ref={canvas} />
</>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment