当放大Canvasjs图时,如何在工具提示内容中显示光标选择的Y轴值范围?简单地说,我感兴趣的是自动显示左侧Y轴最小值(Ymin)的值和光标在缩放窗口内选择的右侧Y轴最大值(Ymax)。
另外,如何计算光标在缩放窗口中选择的Ymin和Ymax之间的差异?
答案 0 :(得分:2)
convertPixelToValue()方法可用于获取光标在Y轴上的位置。
将两个文本框的显示属性(用作工具提示)设置为无。
当在绘图区域内发生mousedown事件时,将调用mousedown事件。然后在拖动光标时触发mousemove事件。这又将文本框设置为可见,并且在convertPixeToValue()的帮助下,y轴值将显示在文本框中。在mouseup上,文本框的显示属性将设置为none。
请仔细阅读以下jsfiddle - http://jsfiddle.net/p6dq37tt/
var yMinValue = jQuery("#yMinValue");
var yMaxValue = jQuery("#yMaxValue");
var y1, y2; //To assign the yMin and yMax value to calculate the difference
var dps = [];
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: true,
zoomType: "y",
title: {
text: "Preview y-values while zooming"
},
subtitles: [{
text: "Click and drag to see the values"
}],
data: [{
type: "line",
dataPoints: dps
}]
});
chart.render();
function mousemovehandler(e) {
var parentOffset = jQuery(this).parent().offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top
var xValue = Math.round(chart.axisX[0].convertPixelToValue(relX));
var yValue = Math.round(chart.axisY[0].convertPixelToValue(relY));
y1 = yValue;
var valueDiff = y1 - y2; //calculating the difference
if(xValue >= chart.axisX[0].minimum || xValue <= chart.axisX[0].maximum) {
yMinValue.css({
left: e.pageX - 50,
top: e.pageY - 20
}); //assigning the position for the yMinValue
jQuery("#yMinValue").val(yValue);
}
jQuery("#divDifference").val(Math.abs(valueDiff));
jQuery("#yMaxValue").removeClass("textbox"); //removing the textbox class
jQuery("#yMinValue").removeClass("textbox");
}
var parentElement = jQuery(".canvasjs-chart-toolbar");
var childElement = document.getElementsByTagName("button");
//for displaying the yMaxValue when the mousedown event is fired.
jQuery(".canvasjs-chart-canvas").last().on("mousedown", function(e) {
if (childElement[0].getAttribute("state") === "pan") { //checking whether the event trigger is zoom or pan.
var parentOffset = jQuery(this).parent().offset();
var relY = e.pageY - parentOffset.top
var yValue = Math.round(chart.axisY[0].convertPixelToValue(relY));
//assigning value of y2 used to calculate the difference.
y2 = yValue;
yMaxValue.css({
left: e.pageX - 50,
top: e.pageY - 20
});
yMinValue.css({
left: e.pageX - 50,
top: e.pageY - 20
});
//hidding the yMinValue behind the yMaxValue.
var yvalue = document.getElementById("yMaxValue");
yvalue.setAttribute("value", yValue);
jQuery(".canvasjs-chart-canvas").last().on("mousemove", mousemovehandler);
}
});
//To hide toolTips when mouse is released
jQuery(".canvasjs-chart-canvas").last().on("mouseup", function(e) {
jQuery("#yMinValue").addClass("textbox");
jQuery("#yMaxValue").addClass("textbox");
jQuery(".canvasjs-chart-canvas").last().off("mousemove");
});
var xVal = 0;
var yVal = 15;
for (var i = 0; i < 1000; i++) {
yVal = yVal + Math.round(5 + Math.random() * (-5 - 5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
}
chart.render();