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

如何在Chart.js v3.0中打印tooltip回调的context对象内容

你遇到的报错是因为Chart.js的tooltip回调context对象存在循环引用(比如内部包含chart实例、DOM节点等互相引用的属性),JSON.stringify默认无法处理这类结构,所以抛出转换错误。

方案1:直接使用控制台原生对象打印(最推荐)

不要用字符串拼接的方式输出对象,直接将context作为独立参数传给console.log,浏览器控制台会直接输出可交互的对象结构,你可以手动展开查看所有可用属性:
把你的title回调里的打印代码改成:

console.log("the context: ", context)

方案2:自定义序列化处理循环引用

如果你确实需要将对象转为字符串输出,可以写一个过滤循环引用的序列化工具函数:

// 放在代码公共位置
function stringifyIgnoreCircular(target, indent = 2) {
  const visited = new WeakSet()
  return JSON.stringify(target, (key, value) => {
    if (typeof value === 'object' && value !== null) {
      if (visited.has(value)) return '[Circular Reference]'
      visited.add(value)
    }
    return value
  }, indent)
}

调用方式:

console.log("the context: " + stringifyIgnoreCircular(context))

方案3:仅打印你需要的字段

Chart.js tooltip回调的context常用属性是固定的,你可以直接提取需要的字段打印,避开循环引用的部分:

// 示例:打印标题、解析后的值、数据集配置
console.log({
  label: context[0]?.label,
  parsedValue: context[0]?.parsed,
  dataset: context[0]?.dataset
})

额外注意

你的代码里配置项位置有误:maintainAspectRatio、responsive是Chart.js的根配置项,不是plugins的子属性,放在plugins下不会生效,需要挪到和plugins同级的位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:18:04