CODEXE

D3 Brush

Technical points:

Brush must be added in a group

d3 event is brush event when the brush event listener is called.

  1. target - the associated brush behavior.
  2. type - the string “start”, “brush” or “end”; see brush.on.
  3. selection - the current brush selection.
  4. sourceEvent - the underlying input event, such as mousemove or touchmove.

Only define brushX(), the height of selection will be fixed to "height". The d3.event.selection will only return [x0,x1]. After seting brush(), the d3.event.selection will only return [[x0,y0],[x1,y1]]


var brush = d3.brushX()
	.extent([[0,0],[width,height]])//(x0,y0)  (x1,y1)
	.on("end",brushend);//when mouse up, move the selection to the exact tick //start(mouse down), brush(mouse move), end(mouse up)
          	  		


              	var margin = {top: 20, right: 20, bottom: 50, left: 70};
    		var width = 500 - margin.left - margin.right;
		var height = 300 - margin.top - margin.bottom;
		
		var svg = d3.select("#diagram").append("svg")
					.attr("width", width+margin.left+margin.right)
					.attr("height", height+margin.top+margin.bottom)
					.append("g")
					.attr("transform","translate("+margin.left+","+margin.right+")");
		var dataset = [[5, 20], [480, 90], [250, 50], [100, 33], [330, 95],
                [410, 12], [475, 44], [25, 67], [85, 21], [220, 88]];
		
		//add x axis
		var xScale = d3.scaleLinear().range([0,width]).domain([0,d3.max(dataset, function(d){return d[0];})]);
		svg.append("g")
			.attr("transform","translate(0,"+height+")")
			.call(d3.axisBottom(xScale));
		
		var brush = d3.brushX()
					.extent([[0,0],[width,height]])//(x0,y0)  (x1,y1)
					.on("end",brushend);//when mouse up, move the selection to the exact tick //start(mouse down), brush(mouse move), end(mouse up)
		svg.append("g")
			.attr("class","brush")
			.call(brush);
		
		function brushend(){
			if (!d3.event.sourceEvent) return; // Only transition after input.
  			if (!d3.event.selection) return; // Ignore empty selections.
			console.log(d3.event.selection);
			var areaArray = d3.event.selection;//[x0,x1]
			
		}