在 d3 中限制缩放和平移

DeX*_*eX3 4 javascript d3.js

我正在尝试使用 d3 的缩放行为在我的 d3 图表上正确地限制缩放和缩放。我已将问题简化为以下最小可运行示例。我希望用户无法以允许他看到 y 轴上 0 线下方的方式进行缩放。

该示例在非缩放状态下工作,通过设置translateExtent为 svg 的完整高度,但是一旦用户放大一点,这当然会中断。事实上,你放大得越远,你就越能观察到负区域。

我需要设置translateExtent什么?

我在每个缩放事件上重绘线和轴的原因是,通常我使用 react 来渲染我的 svg 并使用 d3 仅用于计算 - 但是我已经删除了对 react 的依赖以提供更简洁的示例。

const data = [ 0, 15, 30, 32, 44, 57, 60, 60, 85];

// set up dimensions and margins
const full = { w: 200, h: 200 };
const pct = { w: 0.7, h: 0.7 };
const dims = { w: pct.w * full.w, h: pct.h * full.h };
const margin = { w: (full.w - dims.w)/2, h: (full.h - dims.h)/2 };

// scales
const x = d3.scaleLinear()
  .rangeRound([0, dims.w])
  .domain([0, data.length]);
  
const y = d3.scaleLinear()
  .rangeRound([dims.h, 0])
  .domain(d3.extent(data));

// axes
const axes = {
  x: d3.axisBottom().scale(x).tickSize(-dims.w),
  y: d3.axisLeft().scale(y).tickSize(-dims.h)
}


const g = d3.select('.center');

// actual "charting area"
g
  .attr('transform', `translate(${margin.w}, ${margin.h})`)
  .attr('width', dims.w)
  .attr('height', dims.h)
  
// x-axis
g.append('g')
.attr('transform', `translate(0, ${dims.h})`)
.attr('class', 'axis x')
.call(axes.x)

// y-axis
g.append('g')
.attr('class', 'axis y')
.call(axes.y)


// generator for the line
const line = d3.line()
  .x( (_, i) => x(i) )
  .y( d => y(d) );

// the actual data path
const path = g
  .append('path')
  .attr('class', 'path')
  .attr('d', line(data))
  .attr('stroke', 'black')
  .attr('fill', 'none')

const zoomBehaviour = d3.zoom()
  .scaleExtent([1, 10])
  .translateExtent([[0,0], [Infinity, full.h]])
  .on('zoom', zoom);
  
d3.select('svg.chart').call(zoomBehaviour);
  
function zoom() {
  const t = d3.event.transform;
  
  const scaledX = t.rescaleX(x);
  const scaledY = t.rescaleY(y);
  axes.x.scale(scaledX);
  axes.y.scale(scaledY);
  d3.select('.axis.x').call(axes.x);
  d3.select('.axis.y').call(axes.y);
  
  line
    .x( (_, i) => scaledX(i) )
    .y( d => scaledY(d) );
  
  const scaledPath = path.attr('d', line(data));
}
Run Code Online (Sandbox Code Playgroud)
body {
  width: 200px;
  height: 200px;
}

svg.chart {
  width: 200px;
  height: 200px;
  border: 1px solid black;
}

.axis line, .axis path {
  stroke: grey;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v4.js"></script>
<body>
<svg class="chart">
  <g class="center"></g>
</svg>
</body>
Run Code Online (Sandbox Code Playgroud)

DeX*_*eX3 5

我能够根据罗伯特提出的建议使其工作。我不得不稍微调整一下条件以适合我的用例:

const dims = /* object holding svg width and height */;
const [xMin, xMax] = this.scales.x.domain().map(d => this.scales.x(d));
const [yMin, yMax] = this.scales.y.domain().map(d => this.scales.y(d));

if (t.invertX(xMin) < 0) {
  t.x = -xMin * t.k;
}
if (t.invertX(xMax) > dims.width) {
  t.x = xMax - dims.width * t.k;
}
if (t.invertY(yMax) < 0) {
  t.y = -yMax * t.k;
}
if (t.invertY(yMin) > dims.height) {
  t.y = yMin - dims.height * t.k;
}
Run Code Online (Sandbox Code Playgroud)