如何将highcharts速度计保持在范围内
问题描述:
我正在动态加载速度计。除了使用Ajax与速度计一起拨打电话的麻烦外,我无法将“针”保持在范围内(0-20)。整数输出显示小于或大于20的数字,因为针在错误的方向上旋转过0或20。我想保持它的0权和20左边我的代码:如何将highcharts速度计保持在范围内
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" >
<title>Tribble Inc Sales Meter</title>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(function() {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'gauge',
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
title: {
text: 'Sales-O-Meter'
},
pane: {
startAngle: -150,
endAngle: 150,
background: [{
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#FFF'],
[1, '#333']
]
},
borderWidth: 0,
outerRadius: '109%'
}, {
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#333'],
[1, '#FFF']
]
},
borderWidth: 1,
outerRadius: '107%'
}, {
// default background
}, {
backgroundColor: '#DDD',
borderWidth: 0,
outerRadius: '105%',
innerRadius: '103%'
}]
},
// the value axis
yAxis: {
min: 0,
max: 20,
minorTickInterval: 'auto',
minorTickWidth: 1,
minorTickLength: 10,
minorTickPosition: 'inside',
minorTickColor: '#666',
tickPixelInterval: 20,
tickWidth: 2,
tickPosition: 'inside',
tickLength: 1,
tickColor: '#666',
labels: {
step: 2,
rotation: 'auto'
},
title: {
text: 'sales/min'
},
plotBands: [{
from: 0,
to: 4,
color: '#DF5353' // green
}, {
from: 4,
to: 8,
color: '#DDDF0D' // yellow
}, {
from: 8,
to: 20,
color: '#55BF3B' // red
}]
},
series: [{
name: 'Speed',
data: [18],
tooltip: {
valueSuffix: ' km/h'
}
}]
},
// Add some life
function (chart) {
setInterval(function() {
var point = chart.series[0].points[0],
newVal,
inc = Math.floor((Math.random() - 1) * 20);
newVal = point.y + inc;
if (newVal < 0 || newVal > 20) {
newVal = point.y - inc;
}
point.update(newVal);
}, 3000);
});
});
</script>
</head>
<body>
<script src="highcharts.js"></script>
<script src="highcharts-more.js"></script>
<!--<script src="exporting.js"></script>-->
<div id="container" style="width: 500px; height: 400px; margin: 0 auto"></div>
</body>
</html>
我不完全知道我在做什么错......也许Math.floor()函数已关闭,但我不这么认为。有人可以帮忙吗?
答
inc = Math.floor((Math.random() - 1) * 20);
newVal = point.y + inc;
if (newVal < 0 || newVal > 20) {
newVal = point.y - inc;
该代码生成负向inc,将其添加到点,使点负,然后将其减去点,使点更积极。它出错了,因为公司可能比点更大。
您需要的算法取决于您希望图表变化的方式。如果你想让针摆动,然后生成一个更小的公司,将其添加到指向,然后边界检查它。
inc = (Math.random() * 2.0)-1.0;
newVal = point.y + inc;
if (newVal < 0 || newVal > 20) {
newVal = point.y - inc;
谢谢Steve。我确实在他们最初做代码的过程中找到了答案。我没有使用Math.round((Math.random()-.5)* 20)。将其舍入到一个整数,并保持0至20之间的任何值。 – Psyllex 2013-03-16 07:55:45