我有一个 Angular 应用程序,使用Chartjs显示条形图。和 angular-chart指令。
我还在条形图上应用了一个 Chartjs 插件,以添加一条水平线,其上方有一个标签。
但是当我将鼠标悬停在图表中的一个条形上之后,标签会向该线移动几个像素:
我找不到原因。以下是重现的问题:http://codepen.io/neptune01/pen/JWEeOZ
和代码:
//angular app ----------------------------------------------------------
angular.module('app', ['chart.js'])
.controller('BarCtrl', ['$scope',
function ($scope) {
$scope.labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
$scope.series = ['Series A'];
$scope.data = [
[65, 59, 80, 81, 56, 55, 40]
];
$scope.options = {
horizontalLine: [{
"y": 60,
"style": "rgba(255,102,102,0.4)",
"text": "Horizontal line"
}]
}
}]);
//horizontal line extension for chart.js ------------------------------
var horizonalLinePlugin = {
afterDraw: function(chartInstance) {
var yScale = chartInstance.scales["y-axis-0"];
var canvas = chartInstance.chart;
var ctx = canvas.ctx;
var index;
var line;
var style;
var labelSize;
if (chartInstance.options.horizontalLine) {
for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
line = chartInstance.options.horizontalLine[index];
if (!line.style) {
style = "rgba(169,169,169, .6)";
} else {
style = line.style;
}
if (line.y) {
yValue = yScale.getPixelForValue(line.y);
} else {
yValue = 0;
}
ctx.lineWidth = 3;
if (yValue) {
ctx.beginPath();
ctx.moveTo(yScale.width, yValue);
ctx.lineTo(canvas.width, yValue);
ctx.strokeStyle = style;
ctx.stroke();
}
if (chartInstance.options.scales.yAxes[0].ticks.fontSize != undefined){
labelSize = parseInt(chartInstance.options.scales.yAxes[0].ticks.fontSize);
} else {
labelSize = parseInt(chartInstance.config.options.defaultFontSize);
}
if (line.text) {
ctx.fillStyle = style;
ctx.fillText(line.text, yScale.width, yValue-labelSize-4);
}
}
return;
};
}
};
Chart.pluginService.register(horizonalLinePlugin);
<div ng-app="app">
<div style="width:500px; height:300px;" ng-controller="BarCtrl">
<canvas id="bar" class="chart chart-bar"
chart-data="data" chart-labels="labels" chart-series="series" chart-options="options">
</canvas>
</div>
</div>
最佳答案
对于任何感兴趣的人 -
发生这种情况是因为 ChartJS 设置 text's baseline当鼠标悬停在图表上时,默认情况下位于顶部
。
要获得正确的行为,您需要在绘制文本之前将文本的基线设置为字母
,例如:
...
ctx.textBaseline = 'alphabetic';
ctx.fillText(text, x, y);
...
这是working example .
关于javascript - Angular 应用程序中的 Chartjs 插件标签在悬停时意外移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42579002/