-
Notifications
You must be signed in to change notification settings - Fork 0
/
line_chart .html
124 lines (86 loc) · 2.23 KB
/
line_chart .html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> React! React</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
<style>
#container {
padding: 50px;
background-color: #EEE;
}
#container {
font-size: 14px;
font-family: sans-serif;
color: #0080A8;
}
</style>
</head>
<body>
<div id="container"></div>
<script type="text/babel">
class LineChart extends React.Component {
constructor(props) {
super(props);
this.canvasRef = React.createRef();
}
componentDidMount() {
this.drawChart();
}
componentDidUpdate() {
this.drawChart();
}
drawChart() {
const canvas = this.canvasRef.current;
const ctx = canvas.getContext('2d');
const data = [12, 19, 3, 5, 2, 3, 8];
const labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
const chartHeight = 200;
const chartWidth = 400;
const maxValue = Math.max(...data);
const scale = chartHeight / maxValue;
const stepSize = chartWidth / (data.length - 1);
ctx.clearRect(0, 0, chartWidth, chartHeight);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.beginPath();
for (let i = 0; i < data.length; i++) {
const x = i * stepSize;
const y = chartHeight - data[i] * scale;
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
ctx.fillText(data[i].toString(), x, y - 10);
}
ctx.stroke();
ctx.strokeStyle = 'black';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0, chartHeight);
ctx.lineTo(chartWidth, chartHeight);
ctx.stroke();
ctx.fillStyle = 'black';
ctx.font = '14px Arial';
for (let i = 0; i < labels.length; i++) {
const x = i * stepSize;
const y = chartHeight + 20;
ctx.fillText(labels[i], x, y, stepSize);
}
}
render() {
return <canvas ref={this.canvasRef} width="400" height="220" />;
}
}
ReactDOM.render(
<div>
<LineChart/>
</div>,
document.querySelector("#container")
);
</script>
</body>
</html>