Last active
December 10, 2015 17:08
-
-
Save shama/4465676 to your computer and use it in GitHub Desktop.
Canvas battery animation for a drone HUD: http://imgur.com/4stMG
This file contains 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
var cv = document.getElementById('cv'); | |
var ctx = cv.getContext('2d'); | |
// HUD object | |
function HUD(ctx, opts) { | |
this.ctx = ctx; | |
this.options = options; | |
} | |
// clear for redraw | |
HUD.prototype.clear = function() { cv.width = cv.width; }; | |
// draw a battery | |
HUD.prototype.battery = function(data) { | |
var x = 0, y = 0, w = 60, h = 30; | |
var o = 0.8; | |
if (data <= 0) data = 0; | |
// battery shape | |
if (data < 25) this.ctx.fillStyle = rgba(255, 125, 0, o); | |
else this.ctx.fillStyle = rgba(255, 255, 255, o); | |
this.ctx.fillRect(x, y, w, h); | |
this.ctx.fillRect(w, h/4, w/12, h/2); | |
this.ctx.clearRect(x+5, y+5, w-10, h-10); | |
// text | |
this.ctx.font = '22px impact'; | |
this.ctx.lineWidth = 2; | |
this.ctx.fillText(data + '%', x+w+15, y+(h/2)+8); | |
// power level | |
if (data < 25) this.ctx.fillStyle = rgba(255, 125, 0, o); | |
else this.ctx.fillStyle = rgba(0, 125, 255, o); | |
this.ctx.fillRect(x+8, y+8, (w-16) * (data/100), h-16); | |
}; | |
// helper for rgba | |
function rgba(r, g, b, a) { | |
return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + (a || 1) + ')'; | |
} | |
var h = new HUD(ctx); | |
var power = 100; | |
setInterval(function() { | |
h.clear(); | |
h.battery(power--); | |
}, 100); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment