Setting transform translate of <g> using Javascript - javascript

What I set for transforming <g> is
const svg = d3.select('target-svg')
const g = d3.select('target-g')
svg.call(d3.zoom().on('zoom', () => {
g.attr('transform', d3.event.transform)
})
Now, I am trying to set transform attribute of <g> svg tag using following sample javascript code.
g.attr('transform', 'translate(100, 100) scale(1)')
The issue is that the <g> tag is transleted fine but when zoom in and out using mouse wheel, the <g> is translated to origin position.
For example, if the origin coordinate of translate of <g> is (0, 0) and I translate it to (100, 100), the <g>'s (x, y) is located (100, 100). But when I zoom it, the <g> is go back to (0, 0).
How can I stop it?

A D3 zoom behavior does not track an element's transform attribute - afterall, a zoom behavior might not alter it (zooming on canvas, changing color or shape on zoom, granularity of data, applying a zoom to different elements rather than the one triggering events, etc).
When you apply a transform with d3.event.transform you are applying the current zoom transform, which starts with a translate of [0,0] and a scale of 1. In other words, unless you specify otherwise, the default initial zoom event with a d3 zoom behavior will always be relative to this initial state. This is why the zoom is not relative to the manually set element's transform value.
To unify a manually set transform attribute and the zoom behavior's transform, use the zoom to manage both. You can manually set the transform attribute of the g with the zoom behavior:
var transform = d3.zoomIdentity.translate([100,100]).scale(1);
svg.call(zoom.transform, transform);
The first line manipulates a d3 zoom identity to create a new transform. The second line applies it, calling a zoom event in the process, which triggers a zoom.on event.
With this approach the zoom manages both the use of manual transform and event based transforms, so that the zoom is never out of date or "unaware" of what transform is currently applied to a selection.
Altogether, this might look like:
var svg = d3.select('body')
.append('svg')
.attr('width',500)
.attr('height',400)
var g = svg.append('g');
var rect = g.append('rect')
.attr('x', 750)
.attr('y', 100)
.attr('height',50)
.attr('width',50);
var zoom = d3.zoom()
.on('zoom', function() {
g.attr('transform',d3.event.transform);
})
var initialTransform = d3.zoomIdentity
.translate(-700,-40)
svg.call(zoom);
svg.call(zoom.transform,initialTransform);
<script src="https://d3js.org/d3.v5.min.js"></script>

Related

Resetting D3s transform attributes

After creating some simulations I was going to remove the transforms on reset (where i can change the simulation). That way the viewport is not looking in a stale location.
I was manually resetting it and it looked good but when i carried out either a drag or a zoom, it would jump back to its old location. I noticed the issue was related to the d3.event.transform properties being maintained. I was thinking that the best course of action would be to reset the properties back to x:0, y:0, scale: 1, but i didnt see much with regard to the transform attribute.
How do i reset this?
The closest i have been able to do would be akin to:
const mySvg; // Native element
const g = d3.select(mySvg).select(":first-child"); // pointing to g, where the transform attribute is applied.
g.attr("transform", "")
which reset it, just for a moment until a tick, or drag or zoom occured which it would snap back to d3.event.transform. How is this resettable?
// This is my zoomable behavior i inject in TS
applyZoomableBehavior(svgElement, containerElement) {
const svg = d3.select(svgElement),
container = d3.select(containerElement),
zoomed = () => {
const trans = d3.event.transform;
container.attr('transform', `translate(${trans.x}, ${trans.y}) scale(${trans.k})`);
},
zoom = d3.zoom().on('zoom', zoomed);
svg.call(zoom);
}
Given that it looks like this is related to event handling, by the source: https://github.com/d3/d3-selection/blob/v1.4.1/README.md#handling-events
I am under the impression that i could submit an event for transform, but I dont really see anything giving the right information.
My goal is that I am going to create a resetViewport function which does just this.
HTML:
<svg #svg>
<g>
<g *ngFor="let node of nodes"></g>
<g *ngFor="let link of links"></g>
</g>
</svg
Code:
resetViewport(svgElement){
const g = d3.select(svgElement).select(":first-child");
// `g` points to the outter g element, the child of svg.
}
I believe the answer to the problem would be involving d3.zoomIdentity
If i want to create this reset function, it would be defined simply as:
resetViewport(svgElement){
const svg = d3.select(svgElement);// svgElement is a nativeElement.
// Need to update the current viewport.
const g = svg.select(":first-child")
g.attr('transform', 'translate(0,0) scale(1.0)');
// The below resets the scale and positioning of the viewport for subsequent move / zoom calls.
const zoom = d3.zoom();
svg.call(zoom.transform, d3.zoomIdentity);
}
So when the reset is called it uses the identity matrix to set the location.

How can I offset the initial starting position of a d3 zoom?

I'm trying to zoom in on an SVG element after having translated it's Matrix, but when I start the initial zoom, the position of the SVG resets to 0,0. I'd like the zoom and pan to start from the moved position on page load.
<svg id="#svg">
<g id="#mainGrid>
....a bunch of SVG
</g>
<svg>
<script>
var winCenterV = $(window).height()/2;
var winCenterH = $(window).width()/2;
//set mainGrid to the center of window using snap.svg
var mainGrid = Snap.select("#mainGrid");
var myMatrix = new Snap.Matrix();
myMatrix.scale(1,1);
myMatrix.translate(winCenterH,winCenterV);
myMatrix.rotate(0);
mainGrid.transform(myMatrix);
//d3 zoom
var svgElement = d3.select("svg");
var gridELement = d3.select("#mainGrid");
svgElement.call(d3.zoom()
.scaleExtent([1 / 2, 4])
.on("zoom", zoomed));
function zoomed() {
gridELement.attr("transform", d3.event.transform);
}
</script>
the "mainGrid" SVG element zooms and pans fine, but it snaps back to it's 0,0 position (top left of browser) during the first zoom mouse click or wheel scroll instead of zooming and panning from the transformed location as set by myMatrix. How can I get the d3.event.transform to start zooming from this offset?
Problem:
The d3 zoom behavior does not track or know about what transforms you've applied to an element. It is initialized with scale equal to 1 and translate equal to 0,0. So, when you use
gridELement.attr("transform", d3.event.transform);
in your zoomed function, you are zooming relative to this initial scale and translate.
Rationale
Not every d3 zoom manipulates the transform of the SVG element it is called on: you may want to have zoom interaction everywhere on a plot, but only zoom the plot area and not the margins. Many d3 zooms don't manipulate any SVG transform: they may use semantic zooming, or the zoom may be altering a canvas rather than SVG, etc. As such, a d3-zoom behavior is independent of any SVG transorm attribute on the element(s) it is called on.
Solution
If your zooming by manipulating the transform attribute of an SVG element, let D3 zoom do all of the manipulation - no need to manipulate it manually and have a zoom, this is how the zoom gets out of step.
So,
You can programmatically trigger a zoom event prior to rendering anything. The easiest way to do so is to use:
selection.call(zoom.transform, d3.zoomIdentity.translate(x,y).scale(k));
This line triggers a zoom event. We can use this prior to rendering anything and rely on the zoomed function to set the initial value of the SVG transform attribute. All subsequent zooms will be relative to this and we can proceed as normal:
var svg = d3.select("svg");
var g = svg.append("g");
// define a zoom behavior:
var zoom = d3.zoom()
.on("zoom", zoomed);
// call the zoom:
svg.call(zoom)
// trigger tha initial zoom with an initial transform.
svg.call(zoom.transform,d3.zoomIdentity.scale(20).translate(-100,-100));
// draw the visualization:
var rect = g.append("rect")
.attr("width", 5)
.attr("height", 5)
.attr("x", 100)
.attr("y", 100);
// zoomed function:
// zoom as normal.
function zoomed() {
g.attr("transform",d3.event.transform);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="500" height="300"></svg>
The above snippet applies an initial zoom (scale 20, translate -100,-100) and uses this as the starting point for the zoom interaction. The comment should help explain the process.
// It appears that you're moving #mainGrid and not #svg. So when you call zoom from svgElement it is zooming from it's 0,0 position.
// Or it may because you don't have pound sign in d3.select
var svgElement = d3.select("#svg");
// Try changing svgElement to gridElement
gridELement.call(d3.zoom()
.scaleExtent([1 / 2, 4])
.on("zoom", zoomed));

Zoom causes graph to go out of the plotting area bounds

I'm having an issue with my graph. When I zoom, the line goes over the edge of the canvas area and over the x/y axis. I tried adding a clippath but that doesn't seem to work. If I inspect the DOM in the debugger I can see the clippath rectangle is position exactly where it needs to be.
//The canvasGroup is the area between the axis
var clipGroup = canvasGroup.append("clipPath")
.attr("id", "canvasGroup-clipPath");
var clipRect = clipGroup.append("rect")
.attr("width", width)
.attr("height", height);
//Function that does the zooming
function doZoom()
{
paths.forEach(function(path)
{
path.attr("transform", d3.event.transform);
});
gX.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));
gY.call(yAxis.scale(d3.event.transform.rescaleY(yScale)));
}
var zoom = d3.zoom()
.scaleExtent([1, 5])
.translateExtent([[0, 0], [width, height]])
.on("zoom", doZoom);
//Register the event listener
canvasGroup.call(zoom);
//now loop over the data sets and plot each one
//For brevity, I'm skipping the loop and only showing the call to create the line
var path = canvasGroup.append("path")
.attr("clip-path", "url(#canvasGroup-clipPath)")
.attr("fill", "steelblue")
.attr("class", "line")
.attr("id", lineId + "-line")
.style("stroke", lineColor)
.style("stroke-width", 1)
.style("fill", "none");
paths.push(path);
path.attr("d", function(d) { return plotline(i)});
Here is how it looks.
Before zoom:
After zoom:
The problem is caused by setting the clipping path on the path representing your data. When applying the clipping path the browser needs to decide which coordinate system should be used for the contents of <clipPath> element. This is controlled by the clipPathUnits attribute which defaults to userSpaceOnUse:
userSpaceOnUse
The contents of the <clippath> element represent values in the current user coordinate system in place at the time when the <clippath> element is referenced (i.e., the user coordinate system for the element referencing the <clippath> element via the clip-path attribute).
When transforming the path in your doZoom() function, you are actually establishing a new coordinate system for the path. And, apart from drawing the path itself, this coordinate system will be used to compute the position and dimension of the clipping path. Thus, by transforming the path according to the zoom behavior, you are applying the same transformation to the clipping path whereby moving it away from the desired position.
Although it is tempting to set the clipPathUnits attribute to its other valid value objectBoundingBox, this is most likely not what you want for this case as it further complicates matters. When setting this value the positions and lengths of the <clipPath>'s contents need to be specified as fractions of the bounding box!
Knowing all this, there is a much easier solution to it! You just need to apply the clip-path to an element which will not be transformed during zooming ,e.g. a parent group. Given the incomplete code you provided, this might very well work by setting the clipping path to canvasGroup:
// Set the clipping path on the parent group.
canvasGroup.attr("clip-path", "url(#canvasGroup-clipPath)")
// Append the path to the group as before.
var path = canvasGroup.append("path")
.attr("fill", "steelblue")
.attr("class", "line")
// ...

D3 Initial Zoom with default mercator projection scale

I'm having an issue specific to scale behavior with a default mercator projection scale value, in my case a pretty ridiculous value (75000), since somehow it was the only way I was able to get my TOPOJson map to be project as anything other than a dot.
I created a projection of a map and want to add zoom and pan. My functions work, all except for the default zoom value. As soon as you scroll to zoom, the value jumps back to the default projection scale value, rather than scaling based on the mouse wheel. I have a feeling that the reason is because in order to get the map to display I needed to make my projection scale value really high (75000).
So when the page loads, the zoom looks fine, like this... but when you try to pan or zoom in or out one mouse wheel click, it jumps to this
I tried to limit the code to just the projection and zoom logic bellow.
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id = "map" style = "float : left; min-width:320px;width :50%;height : 600px;"></div>
<script>
var width = 900,
height = 800;
var projection = d3.geo.mercator()
.center([-73.94, 40.70])
.scale(75000)
.translate([(width/2), (height/2)]);
var svg = d3.select("#map").append("svg")
.attr("viewBox", "0 0 900 800")
.attr("preserveAspectRatio", "xMidYMid meet");
var path = d3.geo.path()
.projection(projection);
var g = svg.append("g")
.attr("transform", "translate(-793.0489643729818,-630.1796382734433)scale(3.01487286910262)");
d3.json("ny.json", function(error, ny) {
g.append("path")
.attr("id", "boroughs")
.datum(topojson.feature(ny, ny.objects.boroughs))
.attr("d", path);
// zoom and pan
var zoom = d3.behavior.zoom()
.on("zoom",function() {
g.attr("transform","translate("+
d3.event.translate.join(",")+")scale("+d3.event.scale+")");
g.selectAll("path")
.attr("d", path.projection(projection));
});
svg.call(zoom)
});
I believe your issue is that you set initial scaling and translate values for your g and then reset them on zoom. For scale, for example:
You set a scale for the g to 3.01 to start:
var g = svg.append("g")
.attr("transform", "translate(-793.0489643729818,-630.1796382734433)scale(3.01487286910262)");
However, the first time you zoom with d3.event, it'll return 0.607 or 1.647, (zoom out, zoom in) both are zoomed out relative to 3.01:
g.attr("transform","translate("+
d3.event.translate.join(",")+")scale("+d3.event.scale+")");
This creates the jump you are seeing, as both scale and translate are reset and thus independent of your initial values. I think the translate value would be ok but you call it on the svg and not the g on which you specify the initial translate.
In any event, it is probably easier to not set an initial transform on your g, instead using the projection to do this (instead of a two step center and zoom with both a projection and a transform). That way you can leave all your code unchanged, save for removing the line setting the initial g transform and a modification to your projection.

Scale is being ignored by d3.behavior.zoom()

I have setup this fiddle to try to figure out why the scale that I pass to d3.behavior.zoom() is being ignored. I am setting the scale to 10 but the effective scale is 1. Then if I try to pan the grid the scale jumps to 10. Same thing happens when I try to zoom the grid. The scale jumps to 10 and then the additional scale is applied. What am I doing wrong? How can I work this out in order to have an effective initial scale value?
You're initializing a var scale = 10 to represent that initial zoom, and you're applying that to zoomer via .scale(10). So zoomer knows the initial scale, but nothing in your code is doing the work of applying the initial scale to the d3 selection vis. The first time the scale is actually applied is once the user interacts, which in turn calls function zoom() {...}, where the scale is finally applied.
The time/place to apply the initial scale, is when you create vis:
//create a group that will hold all the content to be zoomed
var vis = graph.append("svg:g")
.attr("class", "plotting-area")
.attr("transform", "scale(" + scale + ")");// <-- THIS
Here's an updated fiddle

Categories