Advertisement
Guest User

Untitled

a guest
Jul 27th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. In some cases you want to handle zooming and rescale your layout.
  2. But at all examples you can see something like this:
  3. -------
  4. var width = 640;
  5. var height = 480;
  6.  
  7. var outer = d3.select('div')
  8. .append("svg:svg")
  9. .attr("width", width)
  10. .attr("height", height)
  11. .attr("pointer-events", "all");
  12.  
  13. var vis = outer
  14. .append('svg:g')
  15. .call(d3.behavior.zoom().on("zoom", rescale))
  16. .on("dblclick.zoom", null)
  17. .append('svg:g');
  18.  
  19. vis.append('svg:rect')
  20. .attr('width', width)
  21. .attr('height', height)
  22. .attr('fill', 'white');
  23.  
  24. var rescale = function() {
  25. vis.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
  26. };
  27. ------
  28.  
  29. Problem with that way - your rectangle handles dragging and
  30. rescaling too. So if you zoomout, rectangle zoomout too and getting
  31. smaller and as side effect - area that handles dragging/zooming is smaller
  32. now too. Also there is no any restriction on max and min scale.
  33.  
  34. So the more correct way - use differ scale factor for rectangle.
  35.  
  36. Here is more correct behaviour:
  37. -------
  38. var width = 640;
  39. var height = 480;
  40.  
  41. var outer = d3.select(_el)
  42. .append("svg:svg")
  43. .attr("width", width)
  44. .attr("height", height)
  45. .attr("pointer-events", "all");
  46.  
  47. var vis = outer
  48. .append('svg:g')
  49. .call(d3.behavior.zoom().scaleExtent([0.2, 5]).on("zoom", rescale)) // here we set min=0.2 and max=5 scale
  50. .on("dblclick.zoom", null)
  51. .append('svg:g');
  52.  
  53. //here is updated rescale function
  54. var rescale = function() {
  55. vis.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
  56.  
  57. //let's rescale/reposition rectangle that using for dragging
  58. var scale = 1 / d3.event.scale;
  59. vis.selectAll('rect').attr("transform", "translate(" + [-1 * (scale * d3.event.translate[0]), -1 * (scale * d3.event.translate[1])] + ")" + " scale(" + scale + ")");
  60. };
  61. -------
  62.  
  63. So now you have min/max scale for zooming and you
  64. dragging area (your rectangle) correctly scales and fit whole svg area all time.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement