我正在研究具有平移/缩放功能的基本线性图
我设法使缩放达到了我想要的效果,但是当我尝试平移时,它只会沿对角线移动,我不确定为什么。
这是我的缩放功能
function zoomed() {
var transform = d3.event.transform;
var updatedxScale = transform.rescaleX(xScale);
var updatedyScale = transform.rescaleX(yScale);
d3.select("zoom-base").attr("transform", transform);
gX.call(xAxis.scale(updatedxScale));
gY.call(yAxis.scale(updatedyScale));
line.x((d, i) => updatedxScale(i)).y(d => updatedyScale(d));
gPath.attr("d", line);
}
以下是更好的上下文https://jsfiddle.net/kaisk/zp5qesL4/
的示例关于如何不受限制地自由平移的任何想法?
答案 0 :(得分:0)
您的代码有很多错误。
zoomed
函数中的行rescaleY
用于y轴g
并将缩放变换应用于此g
这是重构版本,但您需要自己添加一个片段区域。在SO上有足够的示例。
var dataset = ["0.47122", "0.22919", "0.11264", "0.36817", "0.95380", "0.99119", "0.44896", "0.24597", "0.35834", "0.83772", "0.25262", "0.87030", "0.71527", "0.12048", "0.87286", "0.62833", "0.79057", "0.75939", "0.43300", "0.98306", "0.72953"];
var margin = {
top: 10,
right: 10,
bottom: 25,
left: 25
};
var svgWidth = 600;
var svgHeight = 350;
var width = svgWidth - margin.left - margin.right;
var height = svgHeight - margin.top - margin.bottom;
var xScale = d3.scaleLinear()
.domain([0, dataset.length - 1])
.range([0, width]);
var yScale = d3.scaleLinear()
.domain([0, 1])
.range([height, 0]);
var xAxis = d3.axisBottom(xScale);
var yAxis = d3.axisLeft(yScale);
var line = d3.line()
.x((d, i) => xScale(i))
.y(d => yScale(d))
.curve(d3.curveMonotoneX);
var svg = d3.select(".chart").append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var zoom = d3.zoom()
.scaleExtent([0.8, 2])
.on("zoom", zoomed);
var gX = svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var gY = svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var gline = svg.append('g');
var gPath = gline.append("path")
.attr("class", "line")
.attr("d", line(dataset));
d3.select('svg').call(zoom);
function zoomed() {
var transform = d3.event.transform;
var updatedxScale = transform.rescaleX(xScale);
var updatedyScale = transform.rescaleY(yScale);
gPath.attr("transform", transform);
gX.call(xAxis.scale(updatedxScale));
gY.call(yAxis.scale(updatedyScale));
}
.line {
fill: none;
stroke: #4286f4;
stroke-width: 3;
}
.dot {
fill: #4286f4;
stroke: #fff;
}
.view {
fill: #fff;
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<div class="container">
<div class="chart"></div>
</div>