Graph.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. export class Graph {
  2. constructor( maxPoints = 512 ) {
  3. this.maxPoints = maxPoints;
  4. this.lines = {};
  5. this.limit = 0;
  6. this.limitIndex = 0;
  7. this.domElement = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );
  8. this.domElement.setAttribute( 'class', 'graph-svg' );
  9. }
  10. addLine( id, color ) {
  11. const path = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
  12. path.setAttribute( 'class', 'graph-path' );
  13. path.style.stroke = `var(${color})`;
  14. path.style.fill = `var(${color})`;
  15. this.domElement.appendChild( path );
  16. this.lines[ id ] = { path, color, points: [] };
  17. }
  18. addPoint( lineId, value ) {
  19. const line = this.lines[ lineId ];
  20. if ( ! line ) return;
  21. line.points.push( value );
  22. if ( line.points.length > this.maxPoints ) {
  23. line.points.shift();
  24. }
  25. if ( value > this.limit ) {
  26. this.limit = value;
  27. this.limitIndex = 0;
  28. }
  29. }
  30. resetLimit() {
  31. this.limit = 0;
  32. this.limitIndex = 0;
  33. }
  34. update() {
  35. const svgWidth = this.domElement.clientWidth;
  36. const svgHeight = this.domElement.clientHeight;
  37. if ( svgWidth === 0 ) return;
  38. const pointStep = svgWidth / ( this.maxPoints - 1 );
  39. for ( const id in this.lines ) {
  40. const line = this.lines[ id ];
  41. let pathString = `M 0,${ svgHeight }`;
  42. for ( let i = 0; i < line.points.length; i ++ ) {
  43. const x = i * pointStep;
  44. const y = svgHeight - ( line.points[ i ] / this.limit ) * svgHeight;
  45. pathString += ` L ${ x },${ y }`;
  46. }
  47. pathString += ` L ${( line.points.length - 1 ) * pointStep},${ svgHeight } Z`;
  48. const offset = svgWidth - ( ( line.points.length - 1 ) * pointStep );
  49. line.path.setAttribute( 'transform', `translate(${ offset }, 0)` );
  50. line.path.setAttribute( 'd', pathString );
  51. }
  52. //
  53. if ( this.limitIndex ++ > this.maxPoints ) {
  54. this.resetLimit();
  55. }
  56. }
  57. }
粤ICP备19079148号