D3初学者听说尝试创建折线图,以添加新数据并更新该图。通过以this link为例,我编写了以下代码:
import * as d3 from 'd3';
import CreateData from './CreateData';
import { svg } from 'd3';
const MARGIN = {TOP: 50, BOTTOM: 90, LEFT: 75, RIGHT: 50};
const WIDTH = window.innerWidth - MARGIN.LEFT - MARGIN.RIGHT;
const HEIGHT = window.innerHeight - MARGIN.TOP - MARGIN.BOTTOM;
const n = 50;
const duration = 500;
let now = new Date(Date.now() - duration);
const max = 10;
const dataClass = new CreateData(10);
// let data = (dataClass).createTimeData();
let data = d3.range(n).map(function() {return 0;});
export default class LiveD3Chart {
// With a regular javascript class, we need a constructor
constructor (element) {
console.log(data);
this.transition = d3.transition().duration(duration).ease(d3.easeLinear);
this.svg = this.getSvgElement(element);
this.attachClipPath();
this.xScale = this.getScaleX();
this.yScale = this.getScaleY();
this.xAxis = this.getAxisX();
this.yAxis = this.getAxisY();
this.line = this.getLine();
this.path = this.svg.append('g')
.attr('clip-path', 'url(#clip)')
.append('path')
.datum(data)
.attr('class', 'line');
this.tick();
}
getSvgElement(parent) {
var svg = (d3.select(parent)).append('svg')
.attr('width', WIDTH + MARGIN.LEFT + MARGIN.RIGHT)
.attr('height', HEIGHT + MARGIN.TOP + MARGIN.BOTTOM)
.append('g')
.attr('transform', `translate(${MARGIN.LEFT}, ${MARGIN.TOP})`);
return svg;
}
attachClipPath() {
this.svg.append('defs').append('clipPath')
.attr('id', 'clip')
.append('rect')
.attr('width', WIDTH)
.attr('height', HEIGHT);
}
getScaleX() {
var xScale = d3.scaleTime()
//.domain(d3.extent(data, function(d) {return (d.time).getTime() /*- (500 * 2)*/}))
.domain([now - (n - 2) * duration, now - duration])
.range([0, WIDTH]);
return xScale;
}
getScaleY() {
var yScale = d3.scaleLinear()
.domain([0, max])
.range([HEIGHT, 0]);
return yScale;
}
getAxisX() {
var xAxis = this.svg.append('g')
.attr('class', 'x-axis')
.attr('transform', `translate(0, ${HEIGHT})`)
// .transition(this.transition)
.call(this.xScale.axis = d3.axisBottom(this.xScale).tickFormat(10));
return xAxis;
}
getAxisY() {
var yAxis = this.svg.append('g')
//.transition(this.transition)
.attr('class', 'y-axis')
.call(this.yScale.axis = d3.axisLeft(this.yScale).tickFormat(10));
return yAxis;
}
getLine() {
var line = d3.line()
// .x((d) => this.xScale(d.time))
.curve(d3.curveBasis)
.x((d, i) => this.xScale(now - (n - 1 - i) * duration))
.y(d => this.yScale(d.data));
return line;
}
tick() {
this.transition = this.transition.each(() => {
now = new Date();
this.xScale.domain([now - (n - 2) * duration, now - duration]);
data.push(Math.floor(Math.random() * 10));
this.svg.select('.line')
.attr('d', 'line')
.attr('transform', null);
this.xAxis.call(this.xScale.axis);
this.path.transition()
.attr('transform', `translate(${this.xScale(now - (n - 1) * duration)})`);
data.shift();
}).transition().each('start', this.tick());
}
但是,当我使用“ npm start”(响应服务器启动)运行应用程序时,浏览器页面无法加载,并最终出现错误。顺便说一句,如果我创建一个静态图表,它运行良好,因此绝对不是一个反应问题。有什么想法我做错了吗?