1

I have a force layout with a zooming behavior.

var min_zoom = 0.3;
var max_zoom = 3;
var zoom = d3.behavior.zoom().scaleExtent([min_zoom,max_zoom]);

Before form submission, zooming (using the mouse wheel) and translation work just fine just as expected.

svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" +  d3.event.scale + ")" );

To this end, life is good.

When the form is submitted, the current translate and scale values are saved to the session. As an example, say that the current scale is 2. After the submission of the form and loading the page again, the saved scale is applied, restoring the zoom to its state before submission.

However, after this loading of the page, the value for d3.event.scale is set again to its initial value (I guess it is 1). Hence, trying to perform an in or out zoom again (using mouse wheel) applies the scale factor to the initial base value of the zoom (supposedly 1 for d3.event.scale), instead of using the values saved from the session 2, and will make a sudden, unexpected change of the zoom.

PS. Trying to manually assign a value to d3.event.scale doesn't work! I think the most straightforward workaround would be altering d3.event.scale in case that's possible. Otherwise, manually controlling the zoom seems an exhaustive and non-intuitive option to take.

Median Hilal
  • 1,483
  • 9
  • 17
  • 1
    Does this help you? https://stackoverflow.com/questions/16178366/d3-js-set-initial-zoom-level – ksav Oct 23 '18 at 07:47
  • It does the trick... Please post it as an answer so that I can accept it... Thank you! – Median Hilal Oct 25 '18 at 10:33
  • Possible duplicate of [D3.js Set initial zoom level](https://stackoverflow.com/questions/16178366/d3-js-set-initial-zoom-level) – ksav Jan 26 '19 at 17:58

1 Answers1

0

At the creation of your SVG, you need to adjust the transform of your main group as well as set the scale of your zoom.

const previousScale = 2;

const min_scale = 0.3;
const max_scale = 3;

const width = 600;
const height = 200;

var zoom = d3.behavior.zoom()
  .scale(previousScale)
  .scaleExtent([min_scale, max_scale])
  .on('zoom', redraw)

const svg = d3.select('svg')

const g = svg
  .attr('width', width)
  .attr('height', height)
  .append('g')
  .attr('transform', `scale(${previousScale}, ${previousScale})`)
  .call(zoom)

function draw() {
  g.append('circle')
    .attr('r', 50)
    .attr('cx', 50)
    .attr('cy', 50)

  const initialScale = zoom.scale();
  console.log(`initialScale: ${initialScale}`)
}
draw()

function redraw() {
  const newScale = zoom.scale();
  g.attr('transform', `scale(${newScale}, ${newScale})`)
  console.clear()
  console.log(`newScale: ${newScale.toFixed(2)}`)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg></svg>
ksav
  • 20,015
  • 6
  • 46
  • 66