echarts中使用 graphic 绘制矩形 可拖拽 其他方法
时间: 2023-12-11 20:04:58 浏览: 164
使用 echarts 中的 graphic 绘制矩形并可拖拽,可以参考以下步骤:
1. 在 echarts 中添加一个 graphic 组件,并设置其类型为 rect。
```javascript
{
type: 'rect',
id: 'draggableRect',
draggable: true,
shape: {
x: 100,
y: 100,
width: 50,
height: 50
}
}
```
2. 给 graphic 组件添加拖拽事件。
```javascript
myChart.getZr().on('mousemove', function (e) {
if (dragging) {
var target = graphic.get('draggableRect');
var pos = myChart.convertFromPixel({ seriesIndex: 0 }, [e.offsetX, e.offsetY]);
target.attr('position', [pos[0] - startX, pos[1] - startY]);
}
});
```
3. 监听鼠标按下和释放事件,记录拖拽起始位置。
```javascript
var startX, startY, dragging = false;
myChart.getZr().on('mousedown', function (e) {
var target = graphic.get('draggableRect');
if (target) {
var pos = myChart.convertFromPixel({ seriesIndex: 0 }, [e.offsetX, e.offsetY]);
var rectShape = target.shape;
if (pos[0] >= rectShape.x && pos[0] <= rectShape.x + rectShape.width &&
pos[1] >= rectShape.y && pos[1] <= rectShape.y + rectShape.height) {
startX = pos[0] - target.position[0];
startY = pos[1] - target.position[1];
dragging = true;
}
}
});
myChart.getZr().on('mouseup', function (e) {
dragging = false;
});
```
完整代码如下:
```javascript
var myChart = echarts.init(document.getElementById('main'));
myChart.setOption({
graphic: {
elements: [{
type: 'rect',
id: 'draggableRect',
draggable: true,
shape: {
x: 100,
y: 100,
width: 50,
height: 50
},
style: {
fill: '#fff',
stroke: '#000'
}
}]
},
xAxis: {
type: 'value'
},
yAxis: {
type: 'value'
},
series: [{
type: 'scatter',
data: [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]
}]
});
var startX, startY, dragging = false;
myChart.getZr().on('mousedown', function (e) {
var target = myChart.getZr().handler.findHover(e.offsetX, e.offsetY).target;
if (target && target.id === 'draggableRect') {
var pos = myChart.convertFromPixel({ seriesIndex: 0 }, [e.offsetX, e.offsetY]);
var rectShape = target.shape;
if (pos[0] >= rectShape.x && pos[0] <= rectShape.x + rectShape.width &&
pos[1] >= rectShape.y && pos[1] <= rectShape.y + rectShape.height) {
startX = pos[0] - target.position[0];
startY = pos[1] - target.position[1];
dragging = true;
}
}
});
myChart.getZr().on('mouseup', function (e) {
dragging = false;
});
myChart.getZr().on('mousemove', function (e) {
if (dragging) {
var target = myChart.getZr().handler.findHover(e.offsetX, e.offsetY).target;
if (target && target.id === 'draggableRect') {
var pos = myChart.convertFromPixel({ seriesIndex: 0 }, [e.offsetX, e.offsetY]);
target.attr('position', [pos[0] - startX, pos[1] - startY]);
myChart.setOption({
graphic: {
elements: [{
type: 'rect',
id: 'draggableRect',
draggable: true,
shape: {
x: pos[0] - startX,
y: pos[1] - startY,
width: 50,
height: 50
},
style: {
fill: '#fff',
stroke: '#000'
}
}]
}
});
}
}
});
```
这样就能在 echarts 中绘制一个可拖拽的矩形了。
阅读全文