1、首先,在HTML文件中引入Chart.js库:
//这里是随便的一个,可以去Echart官网上下载。这里是网址:Apache ECharts <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
2、在HTML中设置一个容器,用来放置图表:
<div id="main" style="width: 500px;height:600px;"></div> <button id="bar">柱状</button> <button id="line">折线</button>
3、在JS中设置图表:
let myChart = echarts.init(document.getElementById('main')); // 指定图表的配置项和数据 let option = { title: { text: '鞋子' }, tooltip: {}, legend: { data: ['价格'] }, xAxis: { data: array_name //此处为X轴数据,可自行替换 }, yAxis: {}, series: [{ name: '价格', type: 'bar', data: array_price //此处为Y轴数据,可自行替换 } ] }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); //下面是通过按钮改变图表样式: document.getElementById('line').onclick = function() { option.series[0].type = 'line'; console.log(option.series[0].type); myChart.setOption(option); } document.getElementById('bar').onclick = function() { option.series[0].type = 'bar'; console.log(option.series[0].type); myChart.setOption(option); }
这里是数据,及处理后的数据:
let arr = [ { id: 1, name: 'YSL', price: '19.99', num: 59, income: 500 }, { id: 2, name: '胶鞋', price: '79.99', num: 69, income: 250 }, { id: 3, name: '拖鞋', price: '59.99', num: 199, income: 300 }, { id: 4, name: '棉鞋', price: '9.99', num: 299, income: 200 }, { id: 5, name: '豆丁', price: '39.99', num: 99, income: 400 }, { id: 6, name: '长筒靴', price: '99.99', num: 39, income: 570 }, { id: 7, name: '高跟', price: '29.99', num: 19, income: 200 } ] console.log(arr); let array_price = []; let array_name = []; let array_num = []; let array_income = []; for (let i = 0; i < arr.length; i++) { array_price.push(arr[i].price); array_name.push(arr[i].name) array_num.push(arr[i].num) array_income.push(arr[i].income) }