Highcharts是一款流行的JavaScript圖表庫(kù),可以用于創(chuàng)建各種圖標(biāo),包括溫度計(jì)圖表。本文將介紹如何使用Highcharts創(chuàng)建一個(gè)簡(jiǎn)單的溫度計(jì)圖表,并提供具體的代碼示例。
- 準(zhǔn)備工作
首先,需要從Highcharts官方網(wǎng)站(https://www.highcharts.com/download)下載Highcharts庫(kù),并在網(wǎng)頁(yè)中引入相關(guān)的JavaScript和CSS文件。
- 創(chuàng)建HTML元素
接下來(lái),在HTML文件中創(chuàng)建一個(gè)div元素,用于容納溫度計(jì)圖表:
- 配置溫度計(jì)圖表
為了創(chuàng)建溫度計(jì)圖表,需要為Highcharts提供一些數(shù)據(jù)和配置選項(xiàng)。下面是一個(gè)簡(jiǎn)單的示例:
var options = {
chart: {
renderTo: ‘container’,
type: ‘gauge’,
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
title: {
text: ‘Temperature’
},
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%' } ]
登錄后復(fù)制
},
// the value axis
yAxis: {
min: -20, max: 40, minorTickInterval: 'auto', minorTickWidth: 1, minorTickLength: 10, minorTickPosition: 'inside', minorTickColor: '#666', tickInterval: 10, tickWidth: 2, tickPosition: 'inside', tickLength: 12, tickColor: '#666', labels: { step: 2, rotation: 'auto' }, title: { text: '°C' }, plotBands: [{ from: -20, to: 0, color: '#9CCC65' // green }, { from: 0, to: 10, color: '#FFEB3B' // yellow }, { from: 10, to: 20, color: '#FFC107' // orange }, { from: 20, to: 30, color: '#FF5722' // red }, { from: 30, to: 40, color: '#F44336' // dark red }]
登錄后復(fù)制
},
series: [{
name: 'Temperature', data: [20], tooltip: { valueSuffix: ' °C' }
登錄后復(fù)制
}]
};
最重要的是pane,其中定義了內(nèi)外背景顏色、邊框?qū)挾鹊葮邮?。其中plotBands定義了溫度區(qū)間的顏色。后面的yAxis定義了溫度計(jì)的刻度等樣式,series中設(shè)置了溫度計(jì)的初始值。
- 渲染溫度計(jì)圖表
最后,調(diào)用Highcharts的chart()函數(shù)以及options對(duì)象,渲染溫度計(jì)圖表:
var chart = new Highcharts.Chart(options);
完整代碼: