Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

486
Visualizações
How to create rectangles on canvas as in a graph (picture)

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda