Angular 7 D3|SVG Text Element D3|D3| D3 Part10

SVG Text Element and D3


Before we start to SVG text Element and D3 refer
SVG Text Element and D3
In this Lab, We will cover the SVG's Text Element.The <text> element is used to define a text.
To Write  a text inside the SVG
<svg height="30" width="200">
<text x="0" y="15" fill="blue">Welcome to the SVG Basic's</text>
</svg>
We will experiment with how the text element is going to use as label using D3?
Step 1: Create a div with id circleelementdatabound in html template
<div id="circleelementdatabound" ></div>
Step 2: Import D3 in required component.ts
import * as d3 from 'd3';
Step 3: Create user defined class
export class D3lab10 {
public xpos: number = 0;
public ypos: number = 0;
public radious: number = 0;
public highlight: string ='';
public label: string ='';
}
Step 4: Create a  dataset as below
export const lab10data:D3lab10[] = [
{ xpos: 0,ypos: 0,radious: 0,highlight: 'red',label: ''},
{ xpos: 0,ypos: 0,radious: 0,highlight: 'red',label: ''},
{ xpos: 0,ypos: 0,radious: 0,highlight: 'red',label: ''},
];
Step 5: Inside ngOnInit() method  write the below code
// Div element selected from angular's Component
let divcircleelementdatabound = d3.select('#circleelementdatabound');
// svg element added inside the selected div element
let svgforcircleelements = divcircleelementdatabound.append('svg')
.attr('width', 1000)
.attr('height', 500);
// Dynamic coordinate space
let firstdata: D3lab10 = lab10data[0];
firstdata.xpos = 20;
firstdata.ypos = 20;
firstdata.radious = 10;
firstdata.label = '('+firstdata.xpos+','+firstdata.ypos+')';
for (let i = 1; i < lab10data.length; i++){
let prev: D3lab10 = lab10data[i-1];
let current: D3lab10 = lab10data[i];
current.radious = 10;
current.xpos = prev.xpos+50;
current.ypos = prev.ypos+50;
current.label = '('+current.xpos+','+current.ypos+')';
}
// Apply the Data set to svgforcircleelements
let bluecircleelements = svgforcircleelements.selectAll('circle')
.data(lab10data)
.enter()
.append('circle')
.attr('cx', function (d) { return d.xpos; })
.attr('cy', function (d) { return d.ypos;})
.attr('r',function (d) { return d.radious;})
.attr('stroke','black')
.attr('stroke-width','2')
.style('fill', 'blue');
// append text 
let textements = svgforcircleelements.selectAll('text')
.data(lab10data)
.enter()
.append('text')
.attr('x', function (d) { return d.xpos; })
.attr('y', function (d) { return d.ypos;})
.text(function(d) {return d.label;})
.attr('font-family', 'sans-serif')
.attr('font-size', '20px')
.attr('fill', 'red');
}
Step 6: Run the Project and see the result
Code Action @StackBlitz

No comments

Post Top Ad

Post Bottom Ad