Common Echarts diagrams are based on Canvas or SVG

So here’s a little bit of how it works

A histogram

 <canvas id="bar-chart" width="500" height="500"></canvas>
Copy the code
var data = [16.68.20.30.54];
function drawBar(data) {
  let canvas = document.getElementById("bar-chart");
  let c = canvas.getContext("2d");

  // Set the background
  c.fillStyle = "white";
  c.fillRect(0.0.500.500);

  // Set the column
  c.fillStyle = "blue";
  for (var i = 0; i < data.length; i++) {
    var dp = data[i];
    // The y axis is opposite to the canvas so we need to subtract the height dp*5
    c.fillRect(40 + i * 100.460 - dp * 5.50, dp * 5);
  }

  // Set the axes
  c.fillStyle = "black";
  c.lineWidth = 2.0;
  c.beginPath();
  c.moveTo(30.10);
  c.lineTo(30.460);
  c.lineTo(490.460);
  c.stroke();

  // Set the Y-axis label
  c.fillStyle = "black";
  for (var i = 0; i < 5; i++) {
    c.fillText((4 - i) * 20 + "".4, i * 100 + 60);
    c.beginPath();
    c.moveTo(25, i * 100 + 60);
    c.lineTo(30, i * 100 + 60);
    c.stroke();
  }

  // Set the x label
  for (var i = 0; i < 5; i++) {
    c.fillText(data[i], 60 + i * 100.475);
  }

  c.font = "bold 30px serif";
  c.fillText("Bar chart".200.30);
}

Copy the code

The pie chart

<canvas id="pie-chart" width="500" height="500"></canvas>
Copy the code
var data = [16.68.20.30.54];
function drawPie(data) {
  const colors = ["orange"."green"."blue"."yellow"."teal"];
  let canvas = document.getElementById("pie-chart");
  let c = canvas.getContext("2d");

  // Calculate the sum
  let total = data.reduce((cur, t) = > (t += cur));

  // Draw the pie chart
  let prev = 0; // The current sector starts radian
  for (let i = 0; i < data.length; i++) {
    // End radians
    let angle = prev + (data[i] / total) * Math.PI * 2;

    // Set the color
    c.fillStyle = colors[i % colors.length];

    // Draw the fan
    c.beginPath();
    c.moveTo(250.250);
    c.arc(250.250.150, prev, angle, false);
    c.lineTo(250.250);
    c.fill();
    c.strokeStyle = "black";
    c.stroke();
    prev = angle;
  }

  c.fillText("Pie chart".200.50);
}
Copy the code