angular2使用d3.js

这里写图片描述

引入d3

cnpm install d3 --save
编辑.angular-cli.json, 后重新启动ng serve
{
    "styles": [
    "styles.css"
    ],
    "scripts": [
    "../node_modules/d3/build/d3.js"
    ],
}

创建组件

cd angular2Demo/src/app
ng g component d3-demo
新建渲染类line.chart.ts
declare const d3;
export class LineChart {
    target: HTMLElement;
    data = [
        { x: 0, y: 30 },
        { x: 50, y: 20 },
        { x: 100, y: 40 },
        { x: 150, y: 80 },
        { x: 200, y: 95 }
    ];
    svgWidth = 500;
    svgHeight = 500;
    xAxisWidth = 300;
    yAxisWidth = 300;
    paddingBottom = 30;
    paddingLeft = 30;
    // x轴比例尺
    xScale = d3.scaleLinear()
        .domain([0, 100])
        .range([0, this.xAxisWidth]);
    xAixs = d3.axisBottom()
        .scale(this.xScale)
        .ticks(5);
    // y轴比例尺
    yScale = d3.scaleLinear()
        .domain([100, 0])
        .range([0, this.yAxisWidth]);
    yAixs = d3.axisLeft()
        .scale(this.yScale)
        .ticks(5);
    svg: any;
    constructor(target: HTMLElement) {
        this.target = target;
    }
    render() {
        console.log('start rendering');
        this.svg = d3.select(this.target)
            .attr('width', this.svgWidth)
            .attr('height', this.svgHeight);
        this.svg.append('g')
            .attr('transform', 'translate(' + this.paddingLeft + ',' + (this.svgHeight - this.paddingBottom) + ')')
            .call(this.xAixs);
        this.svg.append('g')
            .attr('transform', 'translate(' + this.paddingLeft + ',' +
                (this.svgHeight - this.yAxisWidth - this.paddingBottom) + ')')
            .call(this.yAixs);

        const line = d3.line()
            .x((d) => {
                return d.x + this.paddingLeft;
            })
            .y((d) => {
                return this.svgHeight - d.y - this.paddingBottom;
            })
            .curve(d3.curveCatmullRom.alpha(0.5));
        this.svg
            .append('path')
            .attr('stroke-width', 2)
            .attr('d', line(this.data))
            .attr('fill', '#5fc')
            .attr('stroke', '#333');
    }
}

编辑d3-demo.component.html
<svg #target ></svg>
编辑d3-demo.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { LineChart } from './line.chart';

@Component({
  selector: 'app-d3-demo',
  templateUrl: './d3-demo.component.html',
  styleUrls: ['./d3-demo.component.css']
})
export class D3DemoComponent implements OnInit {

  chart: LineChart;
  @ViewChild('target') target; // 获得子组件的引用
  constructor() { }

  ngOnInit() {
    this.chart = new LineChart(this.target.nativeElement);
    this.chart.render();
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值