Skip to content

Instantly share code, notes, and snippets.

@pqt
Forked from mgechev/canvas-as-favicon.html
Created August 13, 2021 20:35
Show Gist options
  • Save pqt/3e9ea70a623c05bc77601ece120519d1 to your computer and use it in GitHub Desktop.
Save pqt/3e9ea70a623c05bc77601ece120519d1 to your computer and use it in GitHub Desktop.

Revisions

  1. @mgechev mgechev created this gist Dec 12, 2020.
    38 changes: 38 additions & 0 deletions canvas-as-favicon.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    <link rel="shortcut icon" width=32px>
    <canvas style="display: none" id="loader" width="16" height="16"></canvas>

    <script>
    class Loader {
    constructor(link, canvas) {
    this.link = link;
    this.canvas = canvas;
    this.context = canvas.getContext('2d');
    this.context.lineWidth = 2;
    this.context.strokeStyle = "white";
    }
    setProgress(progress) {
    const startAngle = 1.5 * Math.PI;
    this.context.clearRect(0, 0, 16, 16);
    this.context.beginPath();
    this.context.arc(8, 8, 5, startAngle, (progress * 2 * Math.PI) / 100 + startAngle);
    this.context.stroke();
    this.link.href = this.canvas.toDataURL("image/png"); // update favicon
    }
    }

    const canvas = document.querySelector("#loader");
    const link = document.querySelector('link[rel*="icon"]');
    const loader = new Loader(link, canvas);

    let progress = 0;
    const loading = () => {
    loader.setProgress(progress);
    if (progress >= 100) {
    return;
    }
    progress++;
    requestAnimationFrame(loading);
    }
    loading();
    </script>