Skip to content

Instantly share code, notes, and snippets.

@Daniel15
Last active November 9, 2023 21:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daniel15/10518513 to your computer and use it in GitHub Desktop.
Save Daniel15/10518513 to your computer and use it in GitHub Desktop.
Using Favicon as progress bar
<!DOCTYPE html>
<html>
<head>
<title>Example Page</title>
</head>
<body>
<p>This page uses the favicon as a progress bar. Try clicking the button.</p>
<button onclick="run()">Do something</button>
<script>
var FaviconProgress = function() {
// Create <link> for favicon
this._linkEl = document.createElement('link');
this._linkEl.rel = 'icon';
document.head.appendChild(this._linkEl);
// Initialise canvas
this._canvas = document.createElement('canvas');
this._canvas.width = this._canvas.height = 32;
this._context = this._canvas.getContext('2d');
// Clear the favicon by default
this._linkEl.href = this._canvas.toDataURL('image/png');
};
FaviconProgress.prototype = {
render: function(percent) {
this.clear();
this._renderChart(percent);
this._renderText(percent);
this._linkEl.href = this._canvas.toDataURL('image/png');
},
clear: function() {
this._context.clearRect(0, 0, this._canvas.width, this._canvas.height);
},
_renderChart: function(percent) {
var context = this._context;
var middle = this._canvas.width / 2;
// Render progress
// Start from 12 o'clock (-π/2)
var startAngle = -Math.PI / 2;
var endAngle = startAngle + Math.PI * 2 * percent / 100;
context.fillStyle = '#3B5998';
context.beginPath();
context.moveTo(middle, middle);
context.arc(
/* x */ middle,
/* y */ middle,
/* radius */ middle,
startAngle,
endAngle,
/* antiClockwise */ false
);
context.lineTo(middle, middle);
context.closePath();
context.fill();
},
_renderText: function(percent) {
var context = this._context;
var middle = this._canvas.width / 2;
var text = percent + '%';
context.font = '11px Arial';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.strokeStyle = 'black';
context.lineWidth = 4;
context.strokeText(text, middle, middle);
context.fillStyle = 'white';
context.fillText(text, middle, middle);
}
};
var favicon = new FaviconProgress();
function run() {
var progress = 0;
favicon.render(0);
var timer = window.setInterval(function() {
progress += 5;
favicon.render(progress);
if (progress >= 100) {
window.clearInterval(timer);
}
}, 150);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment