CodingNic

Historical Chart and Final Validation

Draw the Historical Chart

Historical Chart and Final Validation 25 min read

Draw the Historical Chart

Draw the Historical Chart

Open the chart section and build drawChart(r) around the existing <canvas id="chart"> element.

Start by matching the canvas to its displayed size for a crisp result:

javascript
const canvas = $("chart");
const box = canvas.getBoundingClientRect();
const dpr = devicePixelRatio || 1;

canvas.width = box.width * dpr;
canvas.height = box.height * dpr;
const ctx = canvas.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

Then map each data point into chart coordinates and draw:

javascript
ctx.beginPath();
points.forEach((point, index) => {
  if (index) ctx.lineTo(point.x, point.y);
  else ctx.moveTo(point.x, point.y);
});
ctx.strokeStyle = "#66ff73";
ctx.lineWidth = 2.2;
ctx.stroke();

The final implementation also draws horizontal guide lines, labels, a filled area under the line, and the last-point marker.

Test it

Select a pair with available historical data and wait for the request to finish.

Checkpoint

The chart displays the actual historical series returned by the service and redraws after the pair changes.