d3.js v7版本框选的实现(结合cosmograph的api实现框选区域的节点高亮)

场景

该文章中d3.jsV7版本框选的实现是指实现框选功能最终拿到了框选矩形的位置坐标。

最近有需求要求大规模数据的展示,要求能展示几万条节点和几万条边。产品中使用的是g6,貌似会卡顿,领导推荐了一个插件cosmograph,插件的其中一个demo与github地址如下。
插件的demo地址
github地址
回到正题,该插件确实能支持数十万条数据,仅能展示,我们要求要能对图中节点进行一些分析,于是提出添加一个框选功能,框住一些节点和边后,回到我们已经开发的使用g6的那个页面去分析(该页面已经具备一些分析功能)。
于是上网查找和研究cosmograph的demo上的框选,原来是使用d3的brush来实现的框选功能。

解决

第一步:安装d3.js(我安装的最新版V7+)

npm install d3 --save

第二步:引入d3

import * as d3 from 'd3'

第三步:具体代码

html

<canvas id="canvas" />//这是cosmograph的图
<i class="iconfont icon-kuangxuan" @click="brushSelect" /> //框选按钮
<svg id="brushContainer" width="100%" height="100%"></svg> //框选

scss

canvas {
    
    
   width: 100%;
   height: 100%;
}
#brushContainer {
    
    
    position: absolute;
    left: 0;
    top: 0;
    display: none;
}

js

data() {
    
    
	return {
    
    
		canvas: null,
		brushDom: null
	}
},
mounted() {
    
    
	this.graph = Graph // 这是cosmograph的图实例
	this.canvas = document.querySelector('canvas')
},
methods: {
    
    
	// 框选
	brushSelect() {
    
    
	  const _this = this
	  document.getElementById('brushContainer').style.display = 'block'
	  _this.brushDom = d3.select('#brushContainer').append('g').attr('id', 'brush')
	  _this.brushDom.call(
	    d3.brush()
	    .on('end', function() {
    
    
	      const selection = d3.brushSelection(this)
	      _this.selectPointsInArea(selection)//selection是框选矩形的位置坐标,该行是使图中框选节点高亮,使用的是cosmograph的自带的方法
	      _this.cancelBrush()
	    })
	    .extent([
	      [0, 0],
	      [this.canvas.scrollWidth, this.canvas.scrollHeight]
	    ])
	  )
	},
	// 取消框选
	cancelBrush() {
    
    
	  this.brushDom
	  .call(
	    d3.brush()
	    .on('.brush', null)
	    .extent([
	      [0, 0],
	      [0, 0]
	    ])
	  )
	  d3.select('#brushContainer').selectAll('*').remove()
	  this.brushDom.attr('fill', false)
	    .attr('pointer-events', false)
	    .attr('style', false)
	  document.getElementById('brushContainer').style.display = 'none'
	  this.brushDom = null
	},
	// 框选高亮
	selectPointsInArea(selection) {
    
    
	  this.pause() // 暂停图动画
	  this.graph.selectNodesInRange(selection) // cosmograph自带方法(提供框选坐标可以使其节点高亮)
	}
}

总结

图上d3的代码只是做到了框选拿到框选矩形的位置坐标,拿到坐标后的高亮节点和边是使用cosmograph的api来实现的。

猜你喜欢

转载自blog.csdn.net/zhangxiaodui/article/details/127919639