ChartJs 自定义工具提示位置 [英] ChartJs custom tooltip position

查看:17
本文介绍了ChartJs 自定义工具提示位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想为了解决这个问题,我需要使用 https://www.chartjs.org/docs/latest/configuration/tooltip.html#position-modes但是,我无法理解公式应该是什么.

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

<html><头><title>带有自定义工具提示的折线图</title><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.js"></script><脚本>window.chartColors = {红色:'rgb(255, 99, 132)',橙色:'rgb(255, 159, 64)',黄色: 'RGB(255, 205, 86)',绿色:'rgb(75, 192, 192)',蓝色:'rgb(54, 162, 235)',紫色:'rgb(153, 102, 255)',灰色:'RGB(231,233,237)'};window.randomScalingFactor = function() {return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);}</脚本><风格>帆布{-moz 用户选择:无;-webkit 用户选择:无;-ms 用户选择:无;}#chartjs-工具提示 {不透明度:1;位置:绝对;背景:rgba(0, 0, 0, .7);白颜色;边框半径:3px;-webkit-transition:所有 .1s 轻松;过渡:所有 .1s 缓和;指针事件:无;-webkit-transform: 翻译(-50%, 0);变换:翻译(-50%,0);}.chartjs-工具提示键 {显示:内联块;宽度:10px;高度:10px;右边距:10px;}</风格></头><身体><画布id="图表"/><脚本>Chart.defaults.global.pointHitDetectionRadius = 1;var customTooltips = 函数(工具提示){var tooltipEl = document.getElementById('chartjs-tooltip');如果(!tooltipEl){tooltipEl = document.createElement('div');tooltipEl.id = 'chartjs-tooltip';tooltipEl.innerHTML = "<div class='wrapper'></div>"document.body.appendChild(tooltipEl);}//如果没有提示则隐藏if (tooltip.opacity === 0) {工具提示El.style.opacity = 0;返回;}//设置插入符号位置tooltipEl.classList.remove('above', 'below', 'no-transform');如果(工具提示.yAlign){tooltipEl.classList.add(tooltip.yAlign);} 别的 {tooltipEl.classList.add('无转换');}函数getBody(bodyItem){返回bodyItem.lines;}//设置文本如果(工具提示体){var titleLines = tooltip.title ||[];var bodyLines = tooltip.body.map(getBody);var innerHtml = '';titleLines.forEach(函数(标题){innerHtml += '

解决方案

可以通过向 Chart.Tooltip.positioners 映射 (DOC).此函数返回工具提示的 x 和 y 位置.

您可以添加一个自定义的来调整偏移处的 x.一种方法是:

//注册客户定位器Chart.Tooltip.positioners.custom = 函数(元素,位置){如果(!元素.长度){返回假;}变量偏移量 = 0;//根据事件位置向左或向右调整偏移量如果(元素[0]._chart.width/2 > position.x){偏移量 = 20;} 别的 {偏移量 = -20;}返回 {x:位置.x + 偏移量,y:位置.y}}

Fiddle 我创建的示例

希望对你有帮助.

there. I use ChartJS and customise tooltip, but have issue with position first and last tooltip's. Look:

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 but, I cannot understand what the formula should be.

CodePen example - 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>

解决方案

New modes can be defined by adding functions to the Chart.Tooltip.positioners map (DOC). This function returns the x and y position for the tooltip.

You can add a custom one to adjust the x at an offset. One way to do this would be to be:

    //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 example that I created

I hope it helps.

这篇关于ChartJs 自定义工具提示位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆