CODEXE

D3 Zoom

The basic idea of d3 zoom is when you move the diagram, the backend code will calculate the transform (x,y) and scale k.

  1. We can use these data to move the diagram. Just set the transform attribute.
  2.  bars.attr("transform", d3.event.transform);
  3. We can use these data to create a new input (i.e. domain) for the xScale and yScale. And add it to the xAxis and yAxis
  4. xAxisGroup.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));//rescaleX - change the xScale domain with the transforming info
    yAxisGroup.call(yAxis.scale(d3.event.transform.rescaleY(yScale)));//rescaleY - change the yScale domain with the transforming info
                 	

          .tick line{
			opacity: 0.2;
		  }
              

              	var margin = {top: 20, right: 20, bottom: 50, left: 70};
    	var width = 500 - margin.left - margin.right;
		var height = 200 - 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+")");


		//set y scale
		var yScale = d3.scaleLinear().range([0,height]).domain([height,0]);
		//add x axis
		var xScale = d3.scaleLinear().range([0,width]).domain([0,width]);//scaleBand is used for  bar chart
		
		//crate grid 
		var xAxis = d3.axisBottom(xScale).ticks(10).tickSize(-height);
		var xAxisGroup = svg.append("g").call(xAxis)
			.attr("transform","translate(0,"+height+")");
		
		var yAxis = d3.axisLeft(yScale).tickSize(-width);
		var yAxisGroup = svg.append("g").call(yAxis);
		
		svg.append("text").text("Gray line is inner tick")
			.attr("x",0-height/2)
			.attr("y",0-margin.left)
			.attr("dy","1em")
			.style("text-anchor", "middle")
			.attr("transform","rotate(-90)");
		svg.append("text").text("Black outline is outter tick")
			.attr("x",width/2)
			.attr("y",height+margin.bottom)
			.style("text-anchor", "middle");
		
		
		//add zoom function
		var zoom = d3.zoom()
					.scaleExtent([1,30])//can treat as the space between two ticks. sets the scale extent to the specified array of numbers [k0, k1] where k0 is the minimum allowed scale factor and k1 is the maximum allowed scale factor
					.translateExtent([[-width,-height],[2*width,2*height]])//the area top left to bottom right
					.on("zoom",zoomed);
		
		function zoomed() {
		  xAxisGroup.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));//rescaleX - change the xScale domain with the transforming info
		  yAxisGroup.call(yAxis.scale(d3.event.transform.rescaleY(yScale)));//rescaleY - change the yScale domain with the transforming info
		}
		d3.select("svg").call(zoom);