前段时间郭宝坤去北齐了, 好久没更新了, 本章学一下echarts的缩放与拖拽
dataZoom-内置在坐标系中
<template>
<div class="chart" ref="chart"></div>
</template>
<script>
import * as echarts from 'echarts'
let myChart = null, data1 = [],
//随机方法
random = function (max) {
return (Math.random() * max).toFixed(3);
};
//生成随机数据
for (let i = 0; i < 500; i++) {
data1.push([random(15), random(10), random(1)]);
}
const options = {
xAxis: { ... },
yAxis: { ... }, //坐标轴部分参考上一章
dataZoom: {
type: 'inside',
},
series: [
{
type: 'scatter',
data: data1
},
]
}
myChart = echarts.init(chartDom)
myChart.setOption(options)
</script>
参考图
- 设置数据窗口范围表示 0% ~ 100%
dataZoom: [
//控制x轴展示区域
{
...
xAxisIndex: 0,
start: 50, //x轴从50% 位置开始展示
end: 80 //截止到80% 位置
},
//控制y轴展示区域
{
...
yAxisIndex: 0, //当存在多个轴如上一章提到的双y轴 yAxis=[{}, {}], 可以用 [0, 1]数组形式控制
start: 0,
end: 50
}
]
dataZoom-滑动条型
dataZoom: [
{
type: 'slider',
xAxisIndex: 0,
startValue: 40, //绝对值
endValue: 100, //当设置了百分比 这个就失效了
}
]
series: [
{
type: 'bar',
data: [...]
},
]
效果图
也可以同时支持inside 和 slider
dataZoom: [
{
type: 'slider',
...
},
{
type: 'inside',
...
}
]
zoomLock
锁定选择区域(或叫做数据窗口)的大小。
dataZoom: [
{
...
zoomLock: true, //布尔值
//虽然上面加了那个属性但是还是可以通过手动框选某个区域进行放大缩小,
//此时就需要加下面这个属性 禁止手动刷选, 鼠标放上去会发现变成一个哑铃的样子
brushSelect: false
}
]
让我们对比下效果图:
没锁定的效果:
锁定的效果:
可以发现锁定后,拖动窗口变成平移了,不会缩放
拖拽
折线中原生的symbol是没有拖拽功能的,用 graphic 组件,在每个点上面,覆盖一个隐藏的可拖拽的圆点。
let data3 = [[40, -10], [...], ...]
//覆盖一层图层方法
function setCoverChart() {
myChart.setOption({
graphic: data3.map(function (item, index) {
return {
type: 'circle',
//把直角坐标点位换算成像素点位
//第一个参数可以是直角坐标系grid, 还可以是地理坐标系geo 等等
//如果存在多个坐标系, 可以指定gridId: convertToPixel({gridId: 2}, [...])
position: myChart.convertToPixel('grid', item),
shape: {
r: 12 //可拖动点的半径
},
invisible: false,
draggable: true,
ondrag: function () {
console.log(2222, this, this.x)
onPointDragging(index, [this.x, this.y]);
},
z: 10
};
})
})
}
//拖拽方法
function onPointDragging(dataIndex, pos) {
//每次拖动后 把当前像素坐标转化成直角坐标系值, 赋值给data3
data3[dataIndex] = myChart.convertFromPixel('grid', pos);
myChart.setOption({
series: [{
id: 'a',
data: data3
}]
})
}
渲染原生echarts
const options = {
xAxis: {
...
type: 'value',
min: -100,
max: 70,
},
yAxis: {
...
type: 'value',
min: -30,
max: 60,
},
series: [
{
id: 'a',
type: 'line',
symbolSize: 20,
data: data3
}
]
}
myChart.setOption(options)
//需要先渲染原生的再覆盖,执行顺序要控制下
setCoverChart()
效果图
invisible如果设置不可见, 会发现小圆点变成小黑点了默认 { fill: '#000' } 外层大的白色线圈是symbol, 只有黑圈才能拖拽
最后的轻语
狡兔尽、走狗烹;飞鸟尽、良弓藏
不需要打鸟的时候, 就把好弓藏起来, 兔子死光了, 就把猎狗煮了吃掉