Created
August 27, 2015 09:08
-
-
Save shengjie/9fedb8a1d5d8d33a9094 to your computer and use it in GitHub Desktop.
Angular directive draw an circle stats with number and unit inside
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
app.directive("circleStats", function () { | |
return { | |
restriction: 'E', | |
scope: { | |
ngModel: "=" | |
}, | |
link: function (scope, element, attrs) { | |
var canvas = document.createElement("canvas"); | |
var g2d = canvas.getContext("2d"); | |
var h = g2d.canvas.height = 200; | |
var w = g2d.canvas.width = 200; | |
var unit = attrs["unit"]; | |
var centerX = w / 2; | |
var centerY = h / 2; | |
var text1Size = h * .3; | |
var text2Size = h * .08; | |
var textY = centerY + text1Size / 3; | |
var varMax = attrs["max"] || 100; | |
var valueColor = attrs["value-color"] || "#19AA8D"; | |
element.append(canvas); | |
var lp = 0; | |
function draw(p) { | |
p = p || 0; | |
var diff = p - lp; | |
var go = diff / 2, ago = Math.abs(go), sign = go / ago; | |
if (ago < 1) { | |
go = 0; | |
lp = p; | |
} else { | |
if (ago > 2) go = 2 * sign; | |
lp = lp + go; | |
} | |
var startAngle = -Math.PI / 2; | |
var angle = Math.PI * 2 * (lp / varMax); | |
var fullAngle = Math.PI * 2; | |
g2d.beginPath(); | |
g2d.rect(0, 0, w, h); | |
g2d.fillStyle = "#fff"; | |
g2d.closePath(); | |
g2d.fill(); | |
g2d.beginPath(); | |
g2d.arc(centerX, centerY, centerX, 0, fullAngle); | |
g2d.fillStyle = "#000000"; | |
g2d.closePath(); | |
g2d.fill(); | |
g2d.beginPath(); | |
g2d.moveTo(centerX, centerY); | |
g2d.lineTo(centerX, 0); | |
g2d.arc(centerX, centerY, centerX, startAngle, startAngle + angle); | |
g2d.fillStyle = valueColor; | |
g2d.closePath(); | |
g2d.fill(); | |
g2d.beginPath(); | |
g2d.arc(centerX, centerY, centerX * .75, 0, fullAngle); | |
g2d.fillStyle = "#ffffff"; | |
g2d.closePath(); | |
g2d.fill(); | |
g2d.fillStyle = "#000"; | |
g2d.font = text1Size + "px/" + text1Size + "px Arial"; | |
g2d.textAlign = "center"; | |
g2d.textBaseline = "bottom"; | |
g2d.fillText(p, centerX, textY); | |
g2d.fillStyle = "#666"; | |
g2d.font = text2Size + "px/" + text2Size + "px Arial"; | |
g2d.textBaseline = "top"; | |
g2d.fillText(unit, centerX, textY); | |
if (go != 0) setTimeout(function () { | |
draw(p); | |
}, 10); | |
} | |
scope.$watch("ngModel", function (newVal) { | |
draw(newVal); | |
}); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment