Home > Software engineering >  How to create rectangles on canvas as in a graph (picture)
How to create rectangles on canvas as in a graph (picture)

Time:07-13

Can you please tell me how to implement such a graph as in the example? I have the following test data:

[
{
  day: 2,
  sum: 7799857
},
{
  day: 3,
  sum: 6986099      
},
{
  day: 4,
  sum: 6471975,
},
{
  day: 7,
  sum: 5895399,
},
{
  day: 8,
  sum: 5194120,
},
{
  day: 9,
  sum: 4851008,
},
{
  day: 10,
  sum: 4483119,
},
{
  day: 11,
  sum: 3492771,
},
{
  day: 14,
  sum: 2717263,
},
{
  day: 15,
  sum: 1763884,
},
{
  day: 16,
  sum: 1111772,
},
{
  day: 17,
  sum: 148788,
},
...
];

I don’t really understand how to separate them (as in the graph, different rectangles)

The chart looks like this enter image description here

I'll be glad for a hint.

CodePudding user response:

It will be really hard for you to make this using canvas. I would suggest using some library like chart-js which operates on canvas.

I tried to do something with canvas for you, but it seems like your data is not related to the picture you added or there is some algorithm that sum the sums that you didn't provide.

Edit:

Fixed with the data you provided. Dimensions are the same, but I'm not sure if this ratio is really calculated or is it just an accident that the first one is a square.

const data = [{
  day: 22,
  sum: 170.23,
}, {
  day: 36,
  sum: 92.96,
}, {
  day: 40,
  sum: 60.01,
}, {
  day: 48,
  sum: 46.41,
}, ];

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

const ratio = data[0].day / data[0].sum;
let lastDay = 0
const scale = 10

for (const item of data) {
  ctx.fillStyle = 'red';
  const width = (item.day - lastDay) * scale;
  const height = item.sum * ratio * scale;
  ctx.fillRect(lastDay * scale, canvas.height - height, width, height)
  ctx.strokeRect(lastDay * scale, canvas.height - height, width, height)
  lastDay = item.day;
}
canvas {
  border: 1px solid black;
}
<canvas width="500" height="400"></canvas>

  • Related