Last active
December 19, 2019 22:38
-
-
Save rynbyjn/9cffe7932816e97dc4956d58c1b1529b to your computer and use it in GitHub Desktop.
This snippet composites a notification red dot on top of an existing favicon with a transparent border
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import debounce from 'lodash.debounce' | |
export const handleFavNotification = debounce((showDot: boolean) => { | |
const canvas = document.createElement('canvas') | |
canvas.width = 32 | |
canvas.height = 32 | |
const ctx = canvas.getContext('2d') | |
const favicon: HTMLLinkElement | null = document.querySelector( | |
'link[rel="icon"]', | |
) | |
if (!favicon) { | |
return | |
} | |
const baseHref = '/images/favicon.ico' | |
if (favicon) { | |
if (showDot) { | |
const img = new Image() | |
img.crossOrigin = 'anonymous' | |
img.src = baseHref | |
img.onload = function() { | |
if (ctx) { | |
ctx.drawImage( | |
img, | |
0, | |
0, | |
img.width, | |
img.height, | |
0, | |
0, | |
canvas.width, | |
canvas.height, | |
) | |
const drawRedDot = (radius: number) => { | |
ctx.fillStyle = '#f00' | |
ctx.beginPath() | |
ctx.arc(27, 5, radius, 0, 2 * Math.PI, false) | |
ctx.closePath() | |
ctx.fill() | |
} | |
// knock out 6x6 area | |
ctx.globalCompositeOperation = 'destination-out' | |
drawRedDot(6) | |
// fill in same spot, but 1px smaller for transparent stroke | |
ctx.globalCompositeOperation = 'source-over' | |
drawRedDot(5) | |
favicon.setAttribute('href', canvas.toDataURL('image/x-icon')) | |
} | |
} | |
} else { | |
favicon.setAttribute('href', baseHref) | |
} | |
} | |
}, 500) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment