'Creating line graph without library in javascript
I'm making some data visualator for my project. I'm now trying and line graphs but i can make until somewhere. I wondering how i can add texts or hover like functions the code?
My Last Code:
window.onload = () => {
setTimeout(() => {
const datas = [
{
value: 10
},
{
value: 15
},
{
value: 5
},
{
value: 7.5
},
{
value: 1
}
]
const minimum = datas.reduce(
(acc, loc) =>
acc.value < loc.value
? acc
: loc
)
const maximum = datas.reduce(
(acc, loc) =>
acc.value > loc.value
? acc
: loc
)
const c = document.getElementById("canvas")
const ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0, 0);
datas.forEach((data,i) => {
lasty = (c.height - Math.floor(data.value / maximum.value * c.height))
lastx = Math.floor(c.width / datas.length) * i
ctx.lineTo(lastx,lasty)
})
ctx.stroke();
},10)
}
Solution 1:[1]
Use the ctx.fillText(string, x, y) function.
Like that?
Remark: I moved the ctx.moveTo(0,0) line into the loop that removes your first vrtical line: i === 0 && ctx.moveTo(lastx, lasty);
window.onload = () => {
setTimeout(() => {
const datas = [
{
value: 10,
},
{
value: 15,
},
{
value: 5,
},
{
value: 7.5,
},
{
value: 1,
},
];
const minimum = datas.reduce((acc, loc) =>
acc.value < loc.value ? acc : loc
);
const maximum = datas.reduce((acc, loc) =>
acc.value > loc.value ? acc : loc
);
const c = document.getElementById("canvas");
const ctx = c.getContext("2d");
ctx.beginPath();
datas.forEach((data, i) => {
lasty = c.height - Math.floor((data.value / maximum.value) * c.height);
lastx = Math.floor(c.width / datas.length) * i;
i === 0 && ctx.moveTo(lastx, lasty);
ctx.lineTo(lastx, lasty);
ctx.fillText(data.value, lastx + 15, lasty + 10);
});
ctx.stroke();
}, 10);
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="app.js"></script>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
