How to add colorbar legend on openlayers heatmap?

https://openlayers.org/en/latest/examples/heatmap-earthquakes.html

When I reviewed the API documentation for the HeatmapLayer, I couldn’t find any explanation about the legend. While searching for a solution, I managed to create a gradient legend manually, but it doesn’t seem to accurately represent the values derived from the data. Specifically, the part where ctx.fillText(‘7.0’, 25, 140); is used to display min, median, and max values separately makes me question if it’s a proper representation of the heatmap’s data. Therefore, I am looking for a way to implement a legend that reflects changes well when the data provided by OpenLayers changes while using the HeatmapLayer.

const vector = new HeatmapLayer({
  source: new VectorSource({
    url: 'data/kml/2012_Earthquakes_Mag5.kml',
    format: new KML({
      extractStyles: false,
    }),
  }),
  blur: parseInt(blur.value, 10),
  radius: parseInt(radius.value, 10),
  weight: function (feature) {
    // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a
    // standards-violating <magnitude> tag in each Placemark.  We extract it from
    // the Placemark's name instead.
    const name = feature.get('name');
    const magnitude = parseFloat(name.substr(2));
    return magnitude - 5;
  },
});


const updateLegend = function () {
  const canvas = document.getElementById('legend');
  const ctx = canvas.getContext('2d');
  const gradient = ctx.createLinearGradient(0, 0, 0, 150);

  // Example color stops for the legend
  gradient.addColorStop(0, 'rgba(0, 0, 255, 1)');
  gradient.addColorStop(0.5, 'rgba(0, 255, 0, 1)');
  gradient.addColorStop(1, 'rgba(255, 0, 0, 1)');

  ctx.fillStyle = gradient;
  ctx.fillRect(0, 0, 20, 150);

  // Add labels for magnitude values
  ctx.fillStyle = '#000';
  ctx.font = '12px Arial';
  ctx.fillText('5.0', 25, 10);
  ctx.fillText('9.0', 25, 75);
  ctx.fillText('7.0', 25, 140);
};


    <div id="legend-container">
      <canvas id="legend" width="150" height="150"></canvas>
    </div>

here’s what i tried.

https://codesandbox.io/s/heatmap-earthquakes-forked-p6tx9x?file=/main.js:2561-2591

manually drawn gradient legend