d3js zoom svg and axix - javascript

I'm trying to draw an external svg file into a webpage using d3 and make it zoom on scroll.
I followed http://bl.ocks.org/mbostock/3892919 but when i add my svg file it remain fixed and doesn't zoom.
I will draw several svg so i will have an array like this:
var data = []
data.push({
name: "base",
x: 50,
y: 50,
width: 350,
url: 'https://upload.wikimedia.org/wikipedia/commons/1/15/Svg.svg'
});
and draw it with a function:
function add(elements, offsetX = 0, offsetY = 0) {
for (let e of elements) {
d3.xml(e.url, 'image/svg+xml', function(error, xml) {
if (error) {
console.log('error' + error)
throw error;
}
var svgNode = xml.getElementsByTagName('svg')[0];
d3.select(svgNode).attr('id', e.name)
.attr('x', e.x + offsetX)
.attr('y', e.y + offsetY);
svg.node().appendChild(svgNode);
svg.select('#' + e.name)
.attr('width', e.width);
});
}
}
full jsfiddle

I looked around the pan & zoom examples available and this is what I found.
In the zoomed function, there should be a translate and scale on the elements appended, not just the x and y axis.
So, I created a group where to append the elements:
var elementsToScale = svg.append("g").attr("id", "elementsToScale")
And I added the last lines in the zoomed function:
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
var translate = d3.event ? d3.event.translate : "0,0"
var scale = d3.event ? d3.event.scale : "1"
svg.select("#elementsToScale").attr("transform", "translate(" + translate + ")" + " scale(" + scale + ")");
}
And then I changed the add function to append the elements to the elementsToScaleGroup:
d3.xml(el.url, 'image/svg+xml', function(error, xml) {
if (error) {
console.log('error' + error)
throw error;
}
var svgNode = xml.getElementsByTagName('svg')[0];
d3.select(svgNode).attr('id', e.name)
.attr('x', el.x + offsetX)
.attr('y', el.y + offsetY);
elementsToScale.node().appendChild(svgNode);
elementsToScale.select('#' + el.name)
.attr('width', el.width);
});
Here is a working fiddle.
The only thing left is the tween on the elements appended on reset.

Related

dc.js - Rendering two objects (one chart - renders, one shape - doesn't) together in one group?

I have two elements I need to render and a context of the big picture I am trying to achieve (a complete dashboard).
One is a chart that renders fine.
$scope.riskChart = new dc.pieChart('#risk-chart');
$scope.riskChart
.width(width)
.height(height)
.radius(Math.round(height/2.0))
.innerRadius(Math.round(height/4.0))
.dimension($scope.quarter)
.group($scope.quarterGroup)
.transitionDuration(250);
The other is a triangle, to be used for a more complex shape
$scope.openChart = d3.select("#risk-chart svg g")
.enter()
.attr("width", 55)
.attr("height", 55)
.append('path')
.attr("d", d3.symbol('triangle-up'))
.attr("transform", function(d) { return "translate(" + 100 + "," + 100 + ")"; })
.style("fill", fill);
On invocation of render functions, the dc.js render function is recognized and the chart is seen, but the d3.js render() function is not recognized.
How do I add this shape to my dc.js canvas (an svg element).
$scope.riskChart.render(); <--------------Works!
$scope.openChart.render(); <--------------Doesn't work (d3.js)!
How do I make this work?
EDIT:
I modified dc.js to include my custom chart, it is a work in progress.
dc.starChart = function(parent, fill) {
var _chart = {};
var _count = null, _category = null;
var _width, _height;
var _root = null, _svg = null, _g = null;
var _region;
var _minHeight = 20;
var _dispatch = d3.dispatch('jump');
_chart.count = function(count) {
if(!arguments.length)
return _count;
_count = count;
return _chart;
};
_chart.category = function(category) {
if(!arguments.length)
return _category
_category = category;
return _chart;
};
function count() {
return _count;
}
function category() {
return _category;
}
function y(height) {
return isNaN(height) ? 3 : _y(0) - _y(height);
}
_chart.redraw = function(fill) {
var color = fill;
var triangle = d3.symbol('triangle-up');
this._g.attr("width", 55)
.attr("height", 55)
.append('path')
.attr("d", triangle)
.attr("transform", function(d) { return "translate(" + 25 + "," + 25 + ")"; })
.style("fill", fill);
return _chart;
};
_chart.render = function() {
_g = _svg
.append('g');
_svg.on('click', function() {
if(_x)
_dispatch.jump(_x.invert(d3.mouse(this)[0]));
});
if (_root.select('svg'))
_chart.redraw();
else{
resetSvg();
generateSvg();
}
return _chart;
};
_chart.on = function(event, callback) {
_dispatch.on(event, callback);
return _chart;
};
_chart.width = function(w) {
if(!arguments.length)
return this._width;
this._width = w;
return _chart;
};
_chart.height = function(h) {
if(!arguments.length)
return this._height;
this._height = h;
return _chart;
};
_chart.select = function(s) {
return this._root.select(s);
};
_chart.selectAll = function(s) {
return this._root.selectAll(s);
};
function resetSvg() {
if (_root.select('svg'))
_chart.select('svg').remove();
generateSvg();
}
function generateSvg() {
this._svg = _root.append('svg')
.attr({width: _chart.width(),
height: _chart.height()});
}
_root = d3.select(parent);
return _chart;
}
I think I confused matters by talking about how to create a new chart, when really you just want to add a symbol to an existing chart.
In order to add things to an existing chart, the easiest thing to do is put an event handler on its pretransition or renderlet event. The pretransition event fires immediately once a chart is rendered or redrawn; the renderlet event fires after its animated transitions are complete.
Adapting your code to D3v4/5 and sticking it in a pretransition handler might look like this:
yearRingChart.on('pretransition', chart => {
let tri = chart.select('svg g') // 1
.selectAll('path.triangle') // 2
.data([0]); // 1
tri = tri.enter()
.append('path')
.attr('class', 'triangle')
.merge(tri);
tri
.attr("d", d3.symbol().type(d3.symbolTriangle).size(200))
.style("fill", 'darkgreen'); // 5
})
Some notes:
Use chart.select to select items within the chart. It's no different from using D3 directly, but it's a little safer. We select the containing <g> here, which is where we want to add the triangle.
Whether or not the triangle is already there, select it.
.data([0]) is a trick to add an element once, only if it doesn't exist - any array of size 1 will do
If there is no triangle, append one and merge it into the selection. Now tri will contain exactly one old or new triangle.
Define any attributes on the triangle, here using d3.symbol to define a triangle of area 200.
Example fiddle.
Because the triangle is not bound to any data array, .enter() should not be called.
Try this way:
$scope.openChart = d3.select("#risk-chart svg g")
.attr("width", 55)
.attr("height", 55)
.append('path')
.attr("d", d3.symbol('triangle-up'))
.attr("transform", function(d) { return "translate(" + 100 + "," + 100 + ")"; })
.style("fill", fill);

D3: keeping position of SVG's relative while panning and zooming

I'm trying to do a proof of concept of a SVG floorplan that pans and zooms and also have the ability to place markers on top. When zooming/panning happens the marker doesn't stay in position. I understand why this happens but not sure about the best way to keep the marker in position when panning/zooming.
Heres the code:
var svg = d3.select(".floorplan")
.attr("width", "100%")
.attr("height", "100%")
.call(d3.zoom().on("zoom", zoomed))
.select("g")
var marker = d3.selectAll(".marker")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
)
function zoomed() {
svg.attr("transform", d3.event.transform);
}
function dragstarted(d) {
console.log('dragstarted');
}
function dragged(d) {
var x = d3.event.x;
var y = d3.event.y;
d3.select(this).attr("transform", "translate(" + x + "," + y + ")");
}
function dragended(d) {
console.log('drag ended: marker:'+ d3.select(this).attr('data-id') + ' position: ' + d3.event.x +', ' + d3.event.y);
}
Theres also a codepen to visually see here: https://codepen.io/danielhoff/pen/WzQbRr
I have an additional constraints that the marker element shouldn't be contained inside the floorplan svg.
Here is a modified version of your codepen which fixes the movements of the marker during drag events while keeping the marker outside the floorplan svg container:
https://codepen.io/xavierguihot/pen/OvyRPY?editors=0010
To bring back into context, an easy solution would have been to include the marker element inside the floorplan container (in order for the marker to get the same zoom events as the floorplan), but here we want the marker to be in its own svg container.
And it is not trivial!
Appart from including ids in html tags (in order to select these elements from the html), only the javascript part has ben modified.
Let's dig a little bit on the steps necessary to get to this point:
First: Let's modify the zoomed function to apply to the marker as well:
Initially this was the zoom function:
function zoomed() {
svg.attr("transform", d3.event.transform);
}
And the modified version:
function zoomed() {
// Before zooming the floor, let's find the previous scale of the floor:
var curFloor = document.getElementById('floorplan');
var curFloorScale = 1;
if (curFloor.getAttribute("transform")) {
var curFloorTransf = getTransformation(curFloor.getAttribute("transform"));
curFloorScale = curFloorTransf.scaleX;
}
// Let's apply the zoom
svg.attr("transform", d3.event.transform);
// And let's now find the new scale of the floor:
var newFloorTransf = getTransformation(curFloor.getAttribute("transform"));
var newFloorScale = newFloorTransf.scaleX;
// This way we get the diff of scale applied to the floor, which we'll apply to the marker:
var dscale = newFloorScale - curFloorScale;
// Then let's find the current x, y coordinates of the marker:
var marker = document.getElementById('Layer_1');
var currentTransf = getTransformation(marker.getAttribute("transform"));
var currentx = currentTransf.translateX;
var currenty = currentTransf.translateY;
// And the position of the mouse:
var center = d3.mouse(marker);
// In order to find out the distance between the mouse and the marker:
// (43 is based on the size of the marker)
var dx = currentx - center[0] + 43;
var dy = currenty - center[1];
// Which allows us to find out the exact place of the new x, y coordinates of the marker after the zoom:
// 38.5 and 39.8 comes from the ratio between the size of the floor container and the marker container.
// "/2" comes (I think) from the fact that the floor container is initially translated at the center of the screen:
var newx = currentx + dx * dscale / (38.5/2);
var newy = currenty + dy * dscale / (39.8/2);
// And we can finally apply the translation/scale of the marker!:
d3.selectAll(".marker").attr("transform", "translate(" + newx + "," + newy + ") scale(" + d3.event.transform.k + ")");
}
This heavily uses the getTransformation function which allows to retrieve the current transform details of an element.
Then: But now, after having zoomed, when we drag the marker, it takes back its original size:
This means we have to tweak the marker's dragg function to keep its current scale when applying the drag transform:
Here was the initial drag function:
function dragged(d) {
var x = d3.event.x;
var y = d3.event.y;
d3.select(this).attr("transform", "translate(" + x + "," + y + ")");
}
And its modified version:
function draggedMarker(d) {
var x = d3.event.x;
var y = d3.event.y;
// As we want to keep the same current scale of the marker during the transform, let's find out the current scale of the marker:
var marker = document.getElementById('Layer_1');
var curScale = 1;
if (marker.getAttribute("transform")) {
curScale = getTransformation(marker.getAttribute("transform")).scaleX;
}
// We can thus apply the translate And keep the current scale:
d3.select(this).attr("transform", "translate(" + x + "," + y + "), scale(" + curScale + ")");
}
Finally: When dragging the floor we also have to drag the marker accordingly:
We thus have to override the default dragging of the floor in order to include the same dragg event to the marker.
Here is the drag function applied to the floor:
function draggedFloor(d) {
// Overriding the floor drag to do the exact same thing as the default drag behaviour^^:
var dx = d3.event.dx;
var dy = d3.event.dy;
var curFloor = document.getElementById('svg-floor');
var curScale = 1;
var curx = 0;
var cury = 0;
if (curFloor.getAttribute("transform")) {
curScale = getTransformation(curFloor.getAttribute("transform")).scaleX;
curx = getTransformation(curFloor.getAttribute("transform")).translateX;
cury = getTransformation(curFloor.getAttribute("transform")).translateY;
}
d3.select(this).attr("transform", "translate(" + (curx + dx) + "," + (cury + dy) + ")");
// We had to override the floor drag in order to include in the same method the drag of the marker:
var marker = document.getElementById('Layer_1');
var currentTransf = getTransformation(marker.getAttribute("transform"));
var currentx = currentTransf.translateX;
var currenty = currentTransf.translateY;
var currentScale = currentTransf.scaleX;
d3.selectAll(".marker").attr("transform", "translate(" + (currentx + dx) + "," + (currenty + dy) + ") scale(" + currentScale + ")");
}

How to implement mouse wheel zoom in D3 like Google Map with overlay and Ctrl + Scroll event?

I implemented zoom with D3 js so whenever the mouse is hover over the canvas the zoom events triggers and allow a user to use the mouse wheel to zoom in and out.
Demo : https://diversity.rcc.uchicago.edu/collapsible_tree
But I want to prevent this default behavior of D3 zoom and need to enforce user to user Ctrl + Scroll to zoom the canvas like google map does : http://jsfiddle.net/maunovaha/jptLfhc8/
Is there anyway we can show the overlay to request a user to do use the combination and then only allow zoom.
My code for zoom is like this:
var svg = d3.select("#collapsible-tree")
.append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.call(zm = d3.behavior.zoom().scaleExtent([0.1, 3]).on("zoom", redraw))
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//Redraw for zoom
function redraw() {
//console.log("here", d3.event.translate, d3.event.scale);
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
I had the same problem a few weeks ago. But i used dagreD3. The function i used are from D3. Here is my working fiddle.
JS Fiddle
// Create a new directed graph
var g = new dagreD3.graphlib.Graph().setGraph({})
.setDefaultEdgeLabel(function() {
return {};
});
// Disable Browserzoom with strg + mousewheel
$(document).keydown(function(event) {
if (event.ctrlKey == true && (event.which == '61' || event.which == '107' || event.which == '173' || event.which == '109' || event.which == '187' || event.which == '189')) {
alert('disabling zooming');
event.preventDefault();
}
});
$(window).bind('mousewheel DOMMouseScroll', function(event) {
if (event.ctrlKey == true) {
event.preventDefault();
}
});
// Check if strg is pressed
var ctrlPressed = false;
$(window).keydown(function(evt) {
if (evt.which == 17) {
ctrlPressed = true;
console.log("pressed");
}
}).keyup(function(evt) {
if (evt.which == 17) {
ctrlPressed = false;
console.log("not pressed");
}
});
//adding nodes and edges
g.setNode(0, {
label: "TOP",
});
g.setNode(1, {
label: "S",
});
g.setNode(2, {
label: "NP",
});
g.setNode(3, {
label: "DT",
});
g.setNode(4, {
label: "This",
});
g.setNode(5, {
label: "VP",
});
g.setNode(6, {
label: "VBZ",
});
g.setNode(7, {
label: "is",
});
g.setNode(8, {
label: "NP",
});
g.setNode(9, {
label: "DT",
});
g.setNode(10, {
label: "an",
});
g.setNode(11, {
label: "NN",
});
g.setNode(12, {
label: "example",
});
g.setNode(13, {
label: ".",
});
g.setNode(14, {
label: "sentence",
});
g.setEdge(3, 4);
g.setEdge(2, 3);
g.setEdge(1, 2);
g.setEdge(6, 7);
g.setEdge(5, 6);
g.setEdge(9, 10);
g.setEdge(8, 9);
g.setEdge(11, 12);
g.setEdge(8, 11);
g.setEdge(5, 8);
g.setEdge(1, 5);
g.setEdge(13, 14);
g.setEdge(1, 13);
g.setEdge(0, 1);
// Round the corners of the nodes
g.nodes().forEach(function(v) {
var node = g.node(v);
node.rx = node.ry = 5;
});
//makes the lines smooth
g.edges().forEach(function(e) {
var edge = g.edge(e.v, e.w);
edge.lineInterpolate = 'basis';
});
// Create the renderer
var render = new dagreD3.render();
var width = 500,
height = 1000,
center = [width / 2, height / 2];
// Set up an SVG group so that we can translate the final graph.
var svg = d3.select("svg"),
inner = svg.append("g");
var zoom = d3.behavior.zoom()
.on("zoom", zoomed);
function zoomed() {
inner.attr("transform", "translate(" + zoom.translate() + ")scale(" + zoom.scale() + ")");
}
svg.call(zoom)
svg.on("wheel.zoom", null);
svg.on("dblclick.zoom", null);
svg.call(zoom.event);
document.getElementById("container").addEventListener("wheel", myFunction);
function myFunction(event) {
if (ctrlPressed == true) {
if (event.wheelDelta > 0) {
zoom_by(1.03);
} else if (event.wheelDelta < 0) {
zoom_by(1 / 1.03);
}
}
}
function zoom_by(factor) {
var scale = zoom.scale(),
extent = zoom.scaleExtent(),
translate = zoom.translate(),
x = translate[0],
y = translate[1],
target_scale = scale * factor;
// If we're already at an extent, done
if (target_scale === extent[0] || target_scale === extent[1]) {
return false;
}
// If the factor is too much, scale it down to reach the extent exactly
var clamped_target_scale = Math.max(extent[0], Math.min(extent[1], target_scale));
if (clamped_target_scale != target_scale) {
target_scale = clamped_target_scale;
factor = target_scale / scale;
}
// Center each vector, stretch, then put back
x = (x - center[0]) * factor + center[0];
y = (y - center[1]) * factor + center[1];
// Enact the zoom immediately
zoom.scale(target_scale)
.translate([x, y]);
zoomed();
}
// Run the renderer. This is what draws the final graph.
render(inner, g);
// Center the graph
var initialScale = 1.0;
zoom.translate([(svg.attr("width") - g.graph().width * initialScale) / 2, 20])
.scale(initialScale)
.event(svg);
svg.attr("height", g.graph().height * initialScale + 40);
You can disable required d3 zoom events by setting that particular event to null.
svg.call(zoom) // zoom disable
.on("wheel.zoom", null)
.on("mousedown.zoom", null)
.on("touchstart.zoom", null)
.on("touchmove.zoom", null)
.on("touchend.zoom", null);
I stumbled upon the same problem and solved it by only conditionally calling the original wheel handler (I am using D3v4):
this.zoom = d3.zoom()[...]
var svg = d3.select(this.$refs.chart)
.call(this.zoom);
var wheeled = svg.on("wheel.zoom");
svg
.on("wheel.zoom", function () {
if (d3.event.ctrlKey) {
wheeled.call(this);
// prevent browser zooming at minimum zoom
d3.event.preventDefault();
d3.event.stopImmediatePropagation();
}
});
Using the latest d3 version and referring to Gniestschow answer
const maxScale=4;
var zoomListener = d3
.zoom()
.scaleExtent([0.1, maxScale])
.on("zoom", zoom);
var svgContainer=d3.select("#container").call(zoomListener);
var svgGroup=svgContainer.append("g")
var wheeled = svgContainer.on("wheel.zoom");
svgContainer
.on("wheel.zoom", null)
window.onkeydown = listenToTheKey;
window.onkeyup = listenToKeyUp;
function listenToTheKey(event) {
if (event.ctrlKey) svgContainer.on("wheel.zoom", wheeled);
}
function listenToKeyUp() {
svgContainer.on("wheel.zoom", null);
}
function zoom(event) {
svgGroup.attr("transform", event.transform.toString());
}

d3.js limit panning in force layout

I am using d3.js with a force layout to visualize a large number of nodes. I would like to implement a limitation to the panning option of the zoom.
JSFiddle : https://jsfiddle.net/40z5tw8h/24/
The above fiddle contains a simple version of what I am working on.
Because I would potentially have to visualize a very large dataset, I use a function to scale down the group holding element ('g') after forces are done. In that way i always have the full visualization visible afterwards.
I would like to limit the panning - when the graph is fully visible, to only be able to move it within the viewport.
In case the layout is zoomed, I would like to limit the panning as follows:
The group holding element should not be able to go:
down more than 20 px from the top of the svg.
right more than 20 px from the left side of the svg.
up more than 20 px from the bottom of the svg.
left more than 20 px from the right side of the svg.
I think all the implementation should be within the zoom function, which for now is:
function zoomed(){
if (d3.event.sourceEvent == null){ //when fitFullGraph uses the zoom
g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
else{
var gElementBounds = g.node().getBoundingClientRect();
var g_bottom = gElementBounds.bottom;
var g_top = gElementBounds.top;
var g_left = gElementBounds.left;
var g_right = gElementBounds.right;
var g_height = gElementBounds.height;
var g_width = gElementBounds.width;
var svg = g.node().parentElement;
var svgElementBounds = svg.getBoundingClientRect();
var svg_bottom = svgElementBounds.bottom;
var svg_top = svgElementBounds.top;
var svg_left = svgElementBounds.left;
var svg_right = svgElementBounds.right;
var svg_height = svgElementBounds.height;
var svg_width = svgElementBounds.width;
var t = d3.event.translate;
var margin = 20;
if(d3.event.sourceEvent.type == 'wheel'){//event is zoom
g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
else{//event is pan
// if(t[0] < svg_left + margin) t[0]= svg_left + margin;
//else if(t[0] > svg_width-g_width - margin) t[0] = svg_width-g_width - margin;
// if(t[1] < g_height +margin) t[1] = g_height + margin;
//else if (t[1] > svg_height - margin) t[1] = svg_height - margin;
//.attr("transform", "translate(" + t+ ")scale(" + d3.event.scale + ")");
//3.event.translate = t;
g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
}
}
The limitations I tried to implement are commented out, because they do not work properly.
Does anyone have a solution?
This is not the complete answer to your question.
I used for block panning to left side translate X scale
var translate = d3.event.translate;
var translateX = translate[0];
var translateY = translate[1];
var scale = d3.event.scale;
var tX = translateX * scale;
var tY = translateY * scale;
console.log('tx', tX, 'ty', tY);
// Do not pan more to left
if (tX> 0) {
g.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
} else {
translate[0] = 0;
g.attr("transform", "translate(" + translate + ") scale(" + d3.event.scale + ")");
}
Which cancels the translation to left but internally it continues. Your user probably stops dragging to the left. Panning to the right gets weird when starting to pan as internally the event has panned far to the left.

D3 behave weird when I do a drag act which also trigger unexpected zoom function

I am yet a noob for d3 and javascript,while I was writing some code to deal with drag the dots and zoom the coordinate, something weird happened, the dots call the drag function,an outer group() element call the zoom, but when I dragging the dot, the outer group change its translate attribute.Code comes below:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>zoom test</title>
</head>
<body></body>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js">
</script>
<script type="text/javascript" charset="utf-8">
function addElem(container,elem){
return container.append(elem);
}
function createLinearScale(dx,dy,rx,ry){
return d3.scale.linear()
.domain([dx,dy])
.range([rx,ry])
}
function appendWithData(container,selector,type,id,classed,dataset){
var result = container.selectAll(selector)
.data(dataset)
.enter()
.append(type);
if(id)
result.attr("id",id);
if(classed)
result.classed(classed,true);
return result;
}
function getElem(selector){
return d3.select(selector);
}
function getAxis(){
return d3.svg.axis();
}
function drag(){
return d3.behavior.drag();
}
function getThis(){
return d3.select("this");
}
function zoom(){
return d3.behavior.zoom();
}
function arrayDelete(array,target,condition){
for (var i = 0, l = array.length; i < l; i ++) {
var v = arr[i];
if((target = v) && condition){
array.splice(i,1);
}
}
}
</script>
<script type="text/javascript" charset="utf-8">
/**
* Set frame for page
*
*/
var body = getElem("body");
var svg = addElem(body,"svg");
var outer = addElem(svg,"g");
var target = addElem(outer,"g");
var x_axis = addElem(target,"g");
var y_axis = addElem(target,"g");
var dots = addElem(target,"g");
var data = [
[ 5, 20 ],
[ 480, 90 ],
[ 250, 50 ],
[ 100, 33 ],
[ 330, 95 ],
[ 410, 12 ],
[ 475, 44 ],
[ 25, 67 ],
[ 85, 21 ],
[ 220, 88 ]
];
/**
* Add axis to chart
*
*/
var height = 500;
var width = 960;
var x_scale = createLinearScale(0, d3.max(data,function(d){return d[0];}) + 50, 0, width - 10);
var y_scale = createLinearScale(0, d3.max(data, function(d){return d[1];}) + 50, height - 10, 0);
var ax_scale = createLinearScale(0, width - 10, 0, d3.max(data,function(d){return d[0];}) + 50);
var ay_scale = createLinearScale(height -10, 0, 0, d3.max(data, function(d){ return d[1];}) + 50);
var xaxis = getAxis().scale(x_scale).orient("bottom").ticks(30);
var yaxis = getAxis().scale(y_scale).orient("right").ticks(10);
x_axis.attr("transform",function(d){return "translate(0," + (height - 10) + ")"}).call(xaxis);
y_axis.attr("transform",function(d){return "translate(0,0)"}).call(yaxis);
/**
* Add dots * */
var dot = appendWithData(dots,"circle","circle","","datum",data);
var text = appendWithData(dots,"text","text","","index",data);
dot.data(data).attr({
"id" : function(d,i){return "datum" +i;},
"tag": function(d,i){return i + "";},
"cx" : function(d){return x_scale(d[0]).toFixed(0)},
"cy" : function(d){return y_scale(d[1]).toFixed(0)},
"fill" : function(d){return "rgb(0," + (d[1] * 5) % 255 + ",53)"},
"r" : 10 });
text.data(data).attr({
"id" : function(d,i){return "index" + i;},
"tag": function(d,i){return i + ""},
"y" : function(d){return y_scale(d[1]).toFixed(0)},
"x" : function(d){return x_scale(d[0]).toFixed(0)},
"transform" : "translate(15,-15)"
})
.text(function(d){return d[0] + "," + d[1]});
var flag = 1;
var drag = drag();
function dragstart(){
console.log("dragstart")
var cur = d3.select(this);
console.log("drag");
cur.transition().ease("elastc").attr({
"r" : 15
});
}
function dragging(){
flag = 0;
var cur = d3.select(this);
var tag = cur.attr("tag");
cir = d3.select("circle[tag='" + tag + "']");
txt = d3.select("text[tag='" + tag + "']");
console.log(cur);
console.log(txt);
var cur_x = d3.event.x;
var cur_y = d3.event.y;
//target.attr("transform","translate(0,0)");
cir.attr({
"cx" : function(d){return cur_x.toFixed(0)},
"cy" : function(d){return cur_y.toFixed(0)},
//"fill" : function(d){return "rgb(0," + (y_scale(cur_y) * 5) % 255 + ",53)"},
});
txt.attr({
"x" : function(d){return cur_x.toFixed(0)},
"y" : function(d){return cur_y.toFixed(0)},
})
.text(new Number(ax_scale(cur_x)).toFixed(0) + "," + new Number(ay_scale(cur_y)).toFixed(0));
}
function dragged(){
var cur = d3.select(this);
cur.transition().ease("elastc").attr({
"r" : 10
});
flag = 1;
}
drag.on("dragstart",dragstart)
.on("drag",dragging)
.on("dragend",dragged);
dot.call(drag);;
var zoom = zoom();
function zoomed(){
//if(flag){
console.log("zoomed");
outer.attr("transform","translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
//}
}
zoom.on("zoom",zoomed);
outer.call(zoom);
</script>
</html>
As you see, I set a toggle(the variable called flag) to solve the trigger problem,but it cause a new problem, I can't zoom with wheel when the mouse is aloft a blank space.
If I understand the question correctly, you want the zooming on the outer while you want dragging on the dots. In that case, there were two problems with your program:
Empty g as the outer: A g element is just an empty container and is unable to capture events inside itself. If you want to capture mouse actions anywhere inside the g, you need to include an invisible background rect inside it with pointer-events: all. Also, you want this element to appear before all other elements in the DOM so that it is indeed in the background:
var bgRect = addElem(outer, "rect");
bgRect.attr('fill', 'none')
.attr('stroke', 'none')
.attr('width', width)
.attr('height', height);
var target = addElem(outer, "g");
// ...
Update: See this question as well: d3.js - mouseover event not working properly on svg group
Transitioning on zooming: The "expected" zoom behavior is that the point under the mouse pointer stays static while everything around the pointer zooms in/out. Hence, the container needs to both scale and transition.
function zoomed(){
console.log("zoomed");
outer.attr("transform","translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
}
However, in your case, you do not want the container to transition so that the axis stays firmly rooted at the origin (0, 0). So:
function zoomed(){
console.log("zoomed");
outer.attr("transform","translate(" + [0,0] + ") scale(" + d3.event.scale + ")");
}
Working demo with these changes: http://jsfiddle.net/S3GsC/

Categories

Resources