目录
D3.js绘图工具系列文章总提纲:【传送门】
我的实现形式是:将其抽离出来为一个方法,然后将图元作为参数传入该方法。
@/D3/utils/drag.js
拖拽方法:
方法一:通过直接赋值拖拽后的位置进行显示:
// 绑定拖拽事件
export default function bindDrag(selection) {
let dragStart = function (d) {
// console.log('拖动开始');
d3.select(this).raise().style("fill", "red");
};
let drag = function (d) {
let { x, y } = d;
d3.select(this).attr("cx", x).attr("cy", y);
};
let dragEnd = function (d) {
// console.log('拖动结束');
d3.select(this).style("fill", "blue");
};
selection.call(d3.drag()
.on("start", dragStart)
.on("drag", drag)
.on("end", dragEnd));
}
方法二:通过加减移动的距离进行赋值后显示:
// 绑定拖拽事件
export default function bindDrag(selection) {
let dragStart = function (event, d) {
d3.select(this).raise().style("fill", "red");
};
let drag = function (event, d) {
let dx = event.dx;
let dy = event.dy;
// 更新圆的位置
d3.select(this)
.attr("cx", function(d) { return +d3.select(this).attr("cx") + dx; })
.attr("cy", function(d) { return +d3.select(this).attr("cy") + dy; });
};
let dragEnd = function (event, d) {
d3.select(this).style("fill", "blue");
};
selection.call(d3.drag()
.on("start", dragStart)
.on("drag", drag)
.on("end", dragEnd));
}
相关实现:
1、生成单个图元并绑定拖拽事件:
import bindDrag from '@/D3/utils/drag';
const svg = d3
.select('#d3Canvas')
.append("svg")
.attr("id", "svg")
.attr("width", 500)
.attr("height", 500)
.attr("viewBox", "0 0 500 500");
// 绘制圆形
drawCircle() {
let circle = svg.append("circle")
.attr("cx", 50)
.attr("cy", 50)
.attr("r", 20)
.style("fill", "blue")
.attr("id", 'circle-1')
// 绑定拖拽事件
bindDrag(circle);
}
效果如下:
2、通过数组集生成多个图元则绑定方法为:
使用形式(@/D3/main.js):
import bindDrag from '@/D3/utils/drag';
const svg = d3
.select('#d3Canvas')
.append("svg")
.attr("id", "svg")
.attr("width", 500)
.attr("height", 500)
.attr("viewBox", "0 0 500 500");
drawCircle() {
// 模拟数据 这里采用比较简单的原点
const dataList = [
{ 'r': 10, 'x': 10, y: 50, 'color': 'blue' },
{ 'r': 20, 'x': 40, y: 50, 'color': 'blue' },
{ 'r': 30, 'x': 90, y: 50, 'color': 'green' },
{ 'r': 15, 'x': 135, y: 50, 'color': 'green' },
{ 'r': 25, 'x': 175, y: 50, 'color': 'red' },
{ 'r': 35, 'x': 235, y: 50, 'color': 'red' },
]
// 绘制图形
const circle = d3.select("svg")
.selectAll("circle")
.data(dataList)
.join("circle")
.attr("r", (d) => d.r)
.attr("cx", (d) => d.x)
.attr("cy", (d) => d.y)
.attr("fill", (d) => d.color)
bindDrag(circle);
}
注:与D3.js Drag相关的API接口可以在这里进行查阅【传送门】