You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chart.js柱状图未渲染数据:比特币矿池可视化异常求助

问题:Chart.js渲染比特币矿池数据柱状图仅显示边框和坐标轴,无柱状条

问题背景

开发加密货币首页时,通过blockchain.com API获取5天内比特币矿池数据,使用Chart.js渲染柱状图,但图表仅显示空白边框和坐标轴,无柱状条。

代码问题分析

  1. 异步执行顺序错误:fetch是异步操作,创建Chart实例时API请求尚未完成,columns数组为空,导致图表无数据。
  2. API字段拼写错误:代码中toFindData["Braiins Poo"]少写了一个字母l,正确字段应为Braiins Pool,会导致该位置数据为undefined。
  3. 页面加载事件错误:document.onload不是标准事件,应使用window.onload或DOMContentLoaded确保DOM加载完成后执行代码。
  4. 缺少Chart.js依赖:HTML中未引入Chart.js脚本,导致无法初始化图表。

修复后的代码

JavaScript代码

var columns = [];
const chartAPI = 'https://api.blockchain.info/pools?timespan=5days';

window.onload = function getData() {
  fetch(chartAPI)
    .then(res => res.json())
    .then(toFindData => {
      // 修正字段拼写错误,按labels顺序添加数据
      columns.push(
        toFindData["AntPool"],
        toFindData["BTC M4"],
        toFindData["Foundry USA"],
        toFindData["ViaBTC"],
        toFindData["Unknown"],
        toFindData["BTC.com"],
        toFindData["F2Pool"],
        toFindData["Binance Pool"],
        toFindData["Mara Pool"],
        toFindData["Poolin"],
        toFindData["SBI Crypto"],
        toFindData["Ultimus"],
        toFindData["Braiins Pool"] // 修正拼写
      );
      
      // 数据获取完成后再创建Chart实例
      const ctx = document.getElementById('chart');
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ['AntPool', 'BTC M4', 'Foundry USA', 'ViaBTC', 'Unknown', 'BTC.com', 'F2Pool', 'Binance Pool', 'Mara Pool', 'Poolin', 'SBI Crypto', 'Ultimus', 'Braiins Pool'],
          datasets: [{
            label: 'BTC矿池算力占比(5天)',
            data: columns,
            borderWidth: 1,
            backgroundColor: 'rgba(54, 162, 235, 0.6)' // 添加背景色让柱状条更明显
          }]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    })
    .catch(err => console.error('API请求失败:', err)); // 添加错误捕获
};

HTML代码(需补充Chart.js依赖)

<div class=" max-w-sm w-full lg:max-w-full lg:flex flex-row">
  <div class="h-48 lg:h-auto lg:w-48 flex-none bg-cover rounded-t lg:rounded-t-none lg:rounded-l text-center overflow-hidden">
  </div>
  <div class="border-2 border-gray-400 lg:border-gray-400 bg-white rounded p-4 flex flex-row justify-between leading-normal">
    <canvas id="chart" width="800" height="400"></canvas>
  </div>
</div>          
<!-- 先引入Chart.js依赖,再引入自定义脚本 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="src/index.js"></script>

关键修复点说明

  • 将Chart实例的创建逻辑移至fetch的then回调内,确保数据加载完成后再渲染图表。
  • 修正矿池名称的拼写错误,避免出现undefined数据。
  • 替换document.onload为window.onload,确保DOM和资源加载完成后执行代码。
  • 在HTML中添加Chart.js的CDN脚本引入,确保Chart.js库可用。
  • 可选:添加柱状条背景色,让图表内容更直观。

内容的提问来源于stack exchange,提问作者C0SM1C0ST

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:15:32