d3 / d3-zoom

Pan and zoom SVG, HTML or Canvas using mouse or touch input.
https://d3js.org/d3-zoom
ISC License
507 stars 143 forks source link

Rescaling a range which max value includes a margin #89

Closed scooterlord closed 7 years ago

scooterlord commented 7 years ago

Hello there, I've been struggling for some time to resolve an issue that seems to be a bug.

Using the following sample code:

var margin = {top: 20, right: 10, bottom: 20, left: 10};
var width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
    .range([0, width]);
var zoom = d3.zoom()
    .scaleExtent([1, 5])
    .translateExtent([[0, 0], [width, height]])
    .on("zoom", zoomed)
function zoomed() {
    (...)
    var xz = d3.event.transform.rescaleX(x);
    (...)
}

In the example above the rescaleX of the x scale also forces the margin included in the width variable to be proportionally scaled. As a result, when zooming in the margin is multiplied *k times (while it should stay the same) and as a result the far right side of the generated shape, eg line is not aligned to the right margin.

mbostock commented 7 years ago

You probably want to define a zoom.extent (related discussion #86) rather than relying on the default:

var zoom = d3.zoom()
    .scaleExtent([1, 5])
    .translateExtent([[0, 0], [width, height]])
    .extent([[0, 0], [width, height]])
    .on("zoom", zoomed);

Please use Stack Overflow tag d3.js to ask for help. Although I make an effort to assist everyone that asks, I am not always available to provide help promptly or directly. Stack Overflow provides a better collaborative forum for self-help: tens of thousands of D3-related questions have already been asked there, and some answered questions may be relevant to you.

When asking for help, please include a link to a live example that demonstrates the issue, preferably on bl.ocks.org. It is often impossible to debug from code snippets alone. Isolate the issue and reduce your code as much as possible before asking for help. The less code you post, the easier it is for someone to debug, and the more likely you are to get a helpful response.

If you have a question about D3’s behavior and want to discuss it with other users, also consider the d3-js Google Group or joining the d3-js Slack.

Thank you! 🤗