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

仅在深色模式(屏幕端)下设置Google Charts图表背景色的方法

问题与解决方案

需求

  • 深色模式下,屏幕显示时图表去除白色背景
  • 打印场景下,无论当前是深浅模式,图表保持原有白色背景

现有问题

  • 设置图表背景为透明:深色模式下背景适配,但部分文本可读性不足
  • 设置半透明背景(fill: "#f2f2f2", fillOpacity: 0.5):屏幕显示效果勉强,但打印时半透明背景会被保留,不符合要求

原始示例代码

HTML

<!-- Load Google Charts in the head -->
<script
  type="text/javascript"
  src="https://www.gstatic.com/charts/loader.js"
></script>

<div class="flex-wrapper">
  <div class="chart" id="chart_div"></div>
  <div class="table-container">
    <h3>Top 10 Talk Details</h3>
    <table>
      <thead>
        <tr>
          <th>No.</th>
          <th>Theme</th>
          <th>Times Given</th>
          <th>Last Invited</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>90</td>
          <td>Lorem ipsum dolor sit amet</td>
          <td>2</td>
          <td>07/01/2024</td>
        </tr>
        <tr>
          <td>101</td>
          <td>Consectetur adipiscing elit</td>
          <td>2</td>
          <td>26/05/2024</td>
        </tr>
        <tr>
          <td>113</td>
          <td>Sed do eiusmod tempor</td>
          <td>2</td>
          <td>02/02/2025</td>
        </tr>
        <tr>
          <td>123</td>
          <td>Incididunt ut labore et dolore</td>
          <td>2</td>
          <td>29/09/2024</td>
        </tr>
        <tr>
          <td>189</td>
          <td>Magna aliqua ut enim ad minim</td>
          <td>2</td>
          <td>12/11/2023</td>
        </tr>
        <tr>
          <td>4</td>
          <td>Veniam quis nostrud exercitation</td>
          <td>1</td>
          <td>08/12/2024</td>
        </tr>
        <tr>
          <td>9</td>
          <td>Ullamco laboris nisi ut aliquip</td>
          <td>1</td>
          <td>31/03/2024</td>
        </tr>
        <tr>
          <td>16</td>
          <td>Ex ea commodo consequat</td>
          <td>1</td>
          <td>11/08/2024</td>
        </tr>
        <tr>
          <td>17</td>
          <td>Duis aute irure dolor in</td>
          <td>1</td>
          <td>15/12/2024</td>
        </tr>
        <tr>
          <td>85</td>
          <td>Reprehenderit in voluptate velit</td>
          <td>1</td>
          <td>24/09/2023</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

CSS

body {
  margin: 0;
  padding: 0;
  font-family: Arial, sans-serif;
  background-color: white;
  color: black;
}

.flex-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: space-between;
  max-width: 900px;
  margin: 40px auto;
}

.chart {
  flex: 1 1 50%;
  min-width: 300px;
  height: 500px;
}

.table-container {
  flex: 1 1 45%;
  min-width: 300px;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

th,
td {
  padding: 10px;
  border: 1px solid #ccc;
  text-align: center;
}

thead tr {
  background-color: #f2f2f2;
}

@media (prefers-color-scheme: dark) {
  body {
    background-color: #121212;
    color: #f0f0f0;
  }

  thead tr {
    background-color: #333;
  }

  td,
  th {
    border-color: #555;
  }
}

@media print {
  .flex-wrapper {
    flex-direction: column;
  }

  .chart,
  .table-container {
    flex: 1 1 100%;
    max-width: 100%;
  }
}

h2,
h3 {
  text-align: center;
}

JavaScript(原始)

google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ["Talk Number", "Times Given"],
    ["No. 90", 2],
    ["No. 101", 2],
    ["No. 113", 2],
    ["No. 123", 2],
    ["No. 189", 2],
    ["No. 4", 1],
    ["No. 9", 1],
    ["No. 16", 1],
    ["No. 17", 1],
    ["No. 85", 1],
  ]);

  var options = {
    title: "Top 10 Most Given Public Talks",
    height: 600,
    fontName: "Arial",
    pieSliceText: "value",
    pieHole: 0.4,
    legend: {
      position: "right",
      alignment: "center",
      textStyle: {
        fontSize: 11,
      },
    },
    chartArea: {
      left: 20,
      top: 60,
      width: "100%",
      height: "80%",
    },
  };

  var chart = new google.visualization.PieChart(
    document.getElementById("chart_div"),
  );
  chart.draw(data, options);
}

修改后的解决方案代码

核心逻辑

  • 用媒体查询检测当前是否为深色模式且非打印状态
  • 动态调整图表背景:仅在深色模式+屏幕显示时用透明背景,其余情况用白色背景
  • 同步修改文本颜色,解决深色模式下透明背景导致的文本可读性问题
  • 监听模式切换和打印事件,实时更新图表

修改后的JavaScript

google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(initChart);

let chartInstance;
let chartData;

function initChart() {
  // 初始化图表数据
  chartData = google.visualization.arrayToDataTable([
    ["Talk Number", "Times Given"],
    ["No. 90", 2],
    ["No. 101", 2],
    ["No. 113", 2],
    ["No. 123", 2],
    ["No. 189", 2],
    ["No. 4", 1],
    ["No. 9", 1],
    ["No. 16", 1],
    ["No. 17", 1],
    ["No. 85", 1],
  ]);

  // 创建图表实例
  chartInstance = new google.visualization.PieChart(
    document.getElementById("chart_div")
  );

  // 首次绘制图表
  updateChart();

  // 监听深色模式切换
  const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)');
  darkModeQuery.addEventListener('change', updateChart);

  // 监听打印状态变化
  window.addEventListener('beforeprint', () => setTimeout(updateChart, 0));
  window.addEventListener('afterprint', updateChart);
}

function updateChart() {
  const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
  const isPrinting = window.matchMedia('print').matches;

  // 设置背景选项
  const backgroundColor = isDarkMode && !isPrinting 
    ? { fill: 'transparent' } 
    : { fill: '#ffffff' };

  // 设置文本颜色
  const textColor = isDarkMode && !isPrinting ? '#f0f0f0' : '#000000';

  const options = {
    title: "Top 10 Most Given Public Talks",
    height: 600,
    fontName: "Arial",
    pieSliceText: "value",
    pieHole: 0.4,
    legend: {
      position: "right",
      alignment: "center",
      textStyle: {
        fontSize: 11,
        color: textColor
      },
    },
    titleTextStyle: { color: textColor },
    pieSliceTextStyle: { color: textColor },
    backgroundColor,
    chartArea: {
      left: 20,
      top: 60,
      width: "100%",
      height: "80%",
    },
  };

  chartInstance.draw(chartData, options);
}

效果说明

  • 深色模式下屏幕显示:图表背景透明,文本自动切换为浅色,保证可读性
  • 打印或浅色模式下:图表保持白色背景,文本为深色,符合常规阅读和打印需求
  • 切换深浅模式或触发打印时,图表会自动更新适配当前状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 16:59:49