Last active
February 3, 2019 16:58
-
-
Save AvocadoVenom/e45a2790c039408e03e45c8e2a1a5c04 to your computer and use it in GitHub Desktop.
Adding labels in the donut hole d3 angular component
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
// Labels | |
private labelValue: any; private labelName: any; | |
private labelPercent: any; private labelTotal: any; | |
private initSvg() { | |
// ... | |
this.labelTotal = this.mainContainer.append('text') | |
.attr('text-anchor', 'middle').style('font-size', '6em') | |
.attr('dy', '.5em').text(this.total); | |
this.labelName = this.mainContainer.append('text') | |
.attr('text-anchor', 'middle').attr('dy', '.4em').attr('dx', '-1em') | |
.style('font-size', '4em').style('opacity', 0); | |
this.labelValue = this.mainContainer.append('text') | |
.attr('text-anchor', 'middle').style('font-size', '2em') | |
.attr('dx', '2em').attr('dy', '.4em').style('opacity', 0); | |
this.labelPercent = this.mainContainer.append('text') | |
.attr('text-anchor', 'middle').attr('dy', '1.7em').style('opacity', 0); | |
} | |
private drawSlices() { | |
// ... | |
this.slices | |
.on('mouseover', function (s) { | |
this.computeLabels(true, s.data); | |
}.bind(this)) | |
.on('mouseout', function () { | |
this.computeLabels(false); | |
}.bind(this)); | |
} | |
private computeLabels(visible: boolean, data?: any) { | |
if (visible) { | |
const percent = (Math.abs(data.abs / this.total) * 100).toFixed(2) + '%'; | |
this.labelName.text(data.name).style('opacity', 1); | |
this.labelValue.text(data.value).style('opacity', 1); | |
this.labelPercent.text(percent).style('opacity', 1); | |
this.labelTotal.style('opacity', 0); | |
} else { | |
[this.labelName, this.labelValue, this.labelPercent].forEach(l => l.style('opacity', 0)); | |
this.labelTotal.style('opacity', 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment