Começando

Este é o código pronto para começar imediatamente a criar os blocos. Esta é a base do Chart.js. Para começar com ele, certifique-se de tê-lo pronto.

Como usar os blocos de configuração (config), renderização (render) e configuração inicial (setup) para desenhar um gráfico no Chart.js

Começando com o Chart JS

Apenas copie o código abaixo e ele criará instantaneamente um gráfico.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Getting Started with Chart JS with www.chartjs3.com</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        font-family: sans-serif;
      }
      .chartMenu {
        width: 100vw;
        height: 40px;
        background: #1A1A1A;
        color: rgba(54, 162, 235, 1);
      }
      .chartMenu p {
        padding: 10px;
        font-size: 20px;
      }
      .chartCard {
        width: 100vw;
        height: calc(100vh - 40px);
        background: rgba(54, 162, 235, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .chartBox {
        width: 700px;
        padding: 20px;
        border-radius: 20px;
        border: solid 3px rgba(54, 162, 235, 1);
        background: white;
      }
    </style>
  </head>
  <body>
    <div class="chartMenu">
      <p>WWW.CHARTJS3.COM (Chart JS <span id="chartVersion"></span>)</p>
    </div>
    <div class="chartCard">
      <div class="chartBox">
        <canvas id="myChart"></canvas>
      </div>
    </div>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script>
    <script>
    // setup 
    const data = {
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      datasets: [{
        label: 'Weekly Sales',
        data: [18, 12, 6, 9, 12, 3, 9],
        backgroundColor: [
          'rgba(255, 26, 104, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(0, 0, 0, 0.2)'
        ],
        borderColor: [
          'rgba(255, 26, 104, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(0, 0, 0, 1)'
        ],
        borderWidth: 1
      }]
    };

    // config 
    const config = {
      type: 'bar',
      data,
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    };

    // render init block
    const myChart = new Chart(
      document.getElementById('myChart'),
      config
    );

    // Instantly assign Chart.js version
    const chartVersion = document.getElementById('chartVersion');
    chartVersion.innerText = Chart.version;
    </script>

  </body>
</html>

Blocos do Chart JS

A documentação do Chart JS está caminhando em direção a blocos. O padrão possui 3 blocos. Estes são o bloco de configuração ou de dados, o bloco de configuração e o bloco de renderização ou de inicialização. Esses 3 blocos são considerados o esqueleto de um gráfico.

Você pode ter mais blocos se necessário. Blocos adicionais geralmente são adicionados quando partes específicas estão se tornando mais expansivas.

Bloco de Configuração ou Bloco de Dados

The setup block is also considered the data block. This block is basically a const (constant variable) that consist multiple javascript objects related to the data. This can be anything from data points, labels, background colors, hover colors and more.

Other const values can be placed in here as well that relate to the values or data points of a chart. The setup block or data block code looks like this and should always be the first part to load. Because all other blocks are dependent on the data block.

    // setup 
    const data = {
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      datasets: [{
        label: 'Weekly Sales',
        data: [18, 12, 6, 9, 12, 3, 9],
        backgroundColor: [
          'rgba(255, 26, 104, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(0, 0, 0, 0.2)'
        ],
        borderColor: [
          'rgba(255, 26, 104, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(0, 0, 0, 1)'
        ],
        borderWidth: 1
      }]
    };

Config Block

The config block consist all the configurations of a chart. The config should be placed before the render block. As this block tend to be depended on the data block due to the data const variable.

The three main parts are the chart type, options and the data variable which links to the setup or data block. You can see in the code that the “data” is a variable which uses ES6 Javascript code.

    // config 
    const config = {
      type: 'bar',
      data,
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    };

We use “data,” only if we have a object value which is EQUAL to the const variable. If the const and object variable are identical we can do this. This means the upper text is a shorthand.

If the const would differ in that case we need to write it in full code like this. You see now that the const and object value differs so we need to write the code more extensive. See below.

    // config 
    const config = {
      type: 'bar',
      data: data2,
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    };

Render Block or Initialization Block

The final block that should always be last is the render or initialization block. This block draws the chart in the canvas based on all the code above. Meaning everything block must be loaded before this block loads. Else it would give an error and might exclude certain blocks of code.

    // render init block
    const myChart = new Chart(
      document.getElementById('myChart'),
      config
    );

The getElementById code refers to the canvas id that is named in the HTML document. In this example it is named “myChart” but you can always change this to anything you prefer. Just ensure you match the canvas id name correctly.

Esta página foi útil?

2 respostas em “Getting Started”

Deixe um comentário