ChartJs自定义工具提示位置

2023-12-21

那里。我使用 ChartJS 并自定义工具提示,但第一个和最后一个工具提示的位置有问题。 看:

enter image description here I suppose that in order to fix the problem, I need to use the https://www.chartjs.org/docs/latest/configuration/tooltip.html#position-modes https://www.chartjs.org/docs/latest/configuration/tooltip.html#position-modes but, I cannot understand what the formula should be.

CodePen 示例 -https://codepen.io/anon/pen/JzRooy https://codepen.io/anon/pen/JzRooy

<html>

<head>
	<title>Line Chart with Custom Tooltips</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.js"></script>
	<script>
	window.chartColors = {
		red: 'rgb(255, 99, 132)',
		orange: 'rgb(255, 159, 64)',
		yellow: 'rgb(255, 205, 86)',
		green: 'rgb(75, 192, 192)',
		blue: 'rgb(54, 162, 235)',
		purple: 'rgb(153, 102, 255)',
		grey: 'rgb(231,233,237)'
	};

	window.randomScalingFactor = function() {
		return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
	}
	</script>
	<style>
		canvas{
			-moz-user-select: none;
			-webkit-user-select: none;
			-ms-user-select: none;
		}
		#chartjs-tooltip {
			opacity: 1;
			position: absolute;
			background: rgba(0, 0, 0, .7);
			color: white;
			border-radius: 3px;
			-webkit-transition: all .1s ease;
			transition: all .1s ease;
			pointer-events: none;
			-webkit-transform: translate(-50%, 0);
			transform: translate(-50%, 0);
		}

		.chartjs-tooltip-key {
			display: inline-block;
			width: 10px;
			height: 10px;
			margin-right: 10px;
		}
	</style>
</head>

<body>
		<canvas id="chart"/>
	<script>
		Chart.defaults.global.pointHitDetectionRadius = 1;

		var customTooltips = function(tooltip) {
			var tooltipEl = document.getElementById('chartjs-tooltip');
			if (!tooltipEl) {
				tooltipEl = document.createElement('div');
				tooltipEl.id = 'chartjs-tooltip';
				tooltipEl.innerHTML = "<div class='wrapper'></div>"
				document.body.appendChild(tooltipEl);
			}

			// Hide if no tooltip
			if (tooltip.opacity === 0) {
				tooltipEl.style.opacity = 0;
				return;
			}

			// Set caret Position
			tooltipEl.classList.remove('above', 'below', 'no-transform');
			if (tooltip.yAlign) {
				tooltipEl.classList.add(tooltip.yAlign);
			} else {
				tooltipEl.classList.add('no-transform');
			}

			function getBody(bodyItem) {
				return bodyItem.lines;
			}

			// Set Text
			if (tooltip.body) {
				var titleLines = tooltip.title || [];
				var bodyLines = tooltip.body.map(getBody);

				var innerHtml = '';

				titleLines.forEach(function(title) {
					innerHtml += '<span style="margin-bottom: 10px;display: inline-block;">' + title + '</span>';
				});
				innerHtml += '<div style="display: flex;flex-direction: row;">';

				bodyLines.forEach(function(body, i) {
					var parts = body[0].split(':');
					innerHtml += '<div style="display: flex;flex-direction: column;margin-right: 10px;font-size: 12px;">';
					innerHtml += '<span>' + parts[0].trim() + '</span>';
					innerHtml += '<b>' + parts[1].trim() + '</b>';
					innerHtml += '</div>';
				});
				innerHtml += '</div>';

				var root = tooltipEl.querySelector('.wrapper');
				root.innerHTML = innerHtml;
			}

			var canvas = this._chart.canvas;
			tooltipEl.style.opacity = 1;
			tooltipEl.style.left = canvas.offsetLeft + tooltip.caretX + 'px';
			tooltipEl.style.top = canvas.offsetTop + tooltip.caretY + 'px';
			tooltipEl.style.fontFamily = tooltip._fontFamily;
			tooltipEl.style.fontSize = tooltip.fontSize;
			tooltipEl.style.fontStyle = tooltip._fontStyle;
			tooltipEl.style.padding = "10px";
			tooltipEl.style.border = "1px solid #B4B6C1";
			tooltipEl.style.backgroundColor = "#FFFFFF";
			tooltipEl.style.color = "#4C4F59";
			tooltipEl.style.fontFamily = '"open sans", "helvetica neue", "arial", "sans-serif"';
		};

		var lineChartData = {
			labels: ["January", "February", "March", "April", "May", "June", "July"],
			datasets: [{
				label: "My First dataset",
				borderColor: window.chartColors.red,
				pointBackgroundColor: window.chartColors.red,
				fill: false,
				data: [
					randomScalingFactor(),
					randomScalingFactor(),
					randomScalingFactor(),
					randomScalingFactor(),
					randomScalingFactor(),
					randomScalingFactor(),
					randomScalingFactor()
				]
			}, {
				label: "My Second dataset",
				borderColor: window.chartColors.blue,
				pointBackgroundColor: window.chartColors.blue,
				fill: false,
				data: [
					randomScalingFactor(),
					randomScalingFactor(),
					randomScalingFactor(),
					randomScalingFactor(),
					randomScalingFactor(),
					randomScalingFactor(),
					randomScalingFactor()
				]
			}]
		};

		window.onload = function() {
			var chartEl = document.getElementById("chart");
			window.myLine = new Chart(chartEl, {
				type: 'line',
				data: lineChartData,
				options: {
					title:{
						display:true,
						text:'Chart.js Line Chart - Custom Tooltips'
					},
					tooltips: {
						enabled: false,
						mode: 'nearest',
						position: 'average',
						intersect: false,
						custom: customTooltips
					}
				}
			});
		};
	</script>
</body>

</html>

可以通过向 Chart.Tooltip.positioners 映射添加函数来定义新模式(DOC https://www.chartjs.org/docs/latest/configuration/tooltip.html#position-modes)。此函数返回工具提示的 x 和 y 位置。

您可以添加一个自定义的来调整 x 的偏移量。 做到这一点的一种方法是:

    //register custome positioner
Chart.Tooltip.positioners.custom = function(elements, position) {
    if (!elements.length) {
      return false;
    }
    var offset = 0;
    //adjust the offset left or right depending on the event position
    if (elements[0]._chart.width / 2 > position.x) {
      offset = 20;
    } else {
      offset = -20;
    }
    return {
      x: position.x + offset,
      y: position.y
    }
  }

Fiddle https://jsfiddle.net/edicarlos10/nj6dfLkt/12/我创建的示例

我希望它有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ChartJs自定义工具提示位置 的相关文章

随机推荐

  • Rails form_for 提交按钮不起作用

    感谢您的耐心等待 对于 Rails 来说还是很陌生 使用 Rails 3 2 为一个简单的应用程序制作注册页面 我的问题是 无论表单中的信息是否有效 表单上的提交按钮都不会产生任何效果 用户模型和数据库似乎都工作正常 如果我从 Rails
  • 保存带有透明度/Alpha 通道的 TIFF

    这是我的问题 我需要创建一个 TIFF 和一个 PNG 其中调色板包含特定颜色和 Alpha 我实际上能够处理 PNG 但不能处理 TIFF 我在互联网上搜索并发现 TIFF 应该处理透明度 但并非所有软件都可以 我尝试了很多方法来加载 T
  • 非标准评估和 PackedArray

    我之前有过asked https stackoverflow com questions 4181470 custom function with non standard evaluation behaves like table怎么做a
  • 更新现有表/模型列/字段?

    如何更新表中的列和列数据类型PeeWee http docs peewee orm com en latest index html 我已经创建了表Person在我的模型的数据库中 但我现在已向模型添加了一些新字段 并更改了某些现有字段 列
  • 在 Golang 中将表单值分配给结构体

    我正在 Golang 中开发 API Rest 我正在使用 Gorm 所以我有代表数据库表的结构 在Create我收到一个带有值的表格 但现在我怀疑如何立即将所有值分配给结构 因为我有一个包含 500 个字段的表 并且我无法逐一进行分配 我
  • 如何在 woocommerce 中获得免费送货的最低订单金额

    我如何获取获得免费送货所需的最低订单金额 woocommerce free shipping min amount在 woocommerce 的管理面板 woocommerce gt 设置 gt 送货 gt 免费送货 gt 最低订单金额 中
  • Ehcache 2 maven依赖

    在我的 pom 中 我有 ehcache 2 依赖项
  • 将 SASS/SCSS 与 Django 集成

    我想将 SASS SCSS 与 Django 应用程序一起使用 我点击了链接https bitbucket org synic django sass https bitbucket org synic django sass 我使用 su
  • 从 C 中的 char* 数组中删除空格

    我正在开发一个插件C对于游戏模拟器 我想在检查输入消息是否包含任何网站网址之前删除聊天消息中的所有空格 所以 我有这样的函数来消除空白 从输入消息中删除空格 char deblank char input int i j char outp
  • 当Android应用程序关闭/设置为后台时如何执行后台任务?

    我的 Android 4 应用程序连接到自定义 Web 服务 用于每隔几分钟同步一次数据 为了确保在线数据始终是最新的 我想在应用程序关闭 发送到后台时触发同步 在 iOS 下这很简单 听applicationDidEnterBackgro
  • 如何将 CloudML Alpha 模型转换为 SavedModel?

    在CloudML在线预测服务的alpha版本中 导出模型的格式为 inputs x x y bytes y g add to collection inputs json dumps inputs outputs a a b bytes b
  • Zabbix JMX Tomcat监控

    我一直在尝试设置 Zabbix 来监控 2 台不同的 Amazon EC2 机器上的 2 台 tomcat 服务器 但没有成功 主机上的 Z 为绿色 但 JMX 为红色并出现这些错误 ZBX TCP READ 失败 4 系统调用中断 其他错
  • 在调整应用程序窗口大小之前,jPanel 不会刷新

    我的 jPanel 有一个问题 我有一个按钮 它从字符串输入 数学公式 中输入 PNG 图像 然后它将在 jPanel 中重新绘制旧图像 问题就来了 图像已更改 但 jPanel 不会重新绘制 直到我手动调整应用程序窗口的大小 看起来面板在
  • 一旦会话过期,Spring MVC 将用户重定向到登录页面

    我在会话中存储了一个用户 bean SessionAttributes UserBean 在我的控制器中 我的目标是在会话过期时将用户重定向到登录 错误页面 以下是我的代码片段 RequestMapping value searchOppo
  • 从 .CSV 文件中选择特定范围的列[重复]

    这个问题在这里已经有答案了 我有一个包含 78000 列的 CSV 文件 我正在尝试选择第 2 100 102 200 列和最后 300 列 其余列需要跳过 我使用 numpy loadtxt 来选择列范围 numpy loadtxt in
  • SignalR 和 .NET 客户端在 ASP.NET WebForms 页面上不起作用

    我尝试在 NET 4 下的 WebForms 应用程序中为仪表板构建通知 我已经下载了 SignalR 版本 1 2 net 客户端和服务器 并准备了一个简单的通知示例 不幸的是它不起作用 我不明白为什么 如果我输入http myserve
  • 如何使用 telnet 测试我的 LDAP 服务器 URL

    我的本地和远程都有一个 LDAP 服务器 我可以 telnet 到本地 ldap url 但无法 telnet 到远程 telnet www ilovebears com 389我得到一个空屏幕 光标闪烁 这是因为某些套接字配置还是端口不可
  • Android getIntent().getExtras() 返回 null

    我正在尝试在两个活动之间传递一个字符串 我已经在其他项目中使用相同的方法完成了此操作 但由于某种原因 当我调用intent getStringExtra String 时 我收到了NullPointerException 我还尝试通过以下方
  • 使用正则表达式验证十六进制字符串

    我正在使用正则表达式验证字符串是否为十六进制 我使用的表达是 A Fa f0 9 当我使用这个时 字符串AABB10被识别为有效的十六进制 但字符串10AABB被认定为无效 我该如何解决这个问题 您很可能需要一个 so regex a fA
  • ChartJs自定义工具提示位置

    那里 我使用 ChartJS 并自定义工具提示 但第一个和最后一个工具提示的位置有问题 看 I suppose that in order to fix the problem I need to use the https www cha