The label on the left most node disappears if the node is partially displayed on the canvas.
How do I resolve this?
Thanks
InfoVis tries to hide the node labels when it asserts that the label would fall off the canvas, if it were to be displayed on the node.
It basically computes the canvas position and dimensions, the node position and dimensions, and tries to see if the label's position is out of the canvas.
This can be seen on placeLabeland fitsInCanvas functions, around lines 9683 and 7669 of the final jit.js file, respectively.
I faced this problem too, while working with SpaceTree visualizations. This became an issue when we tried present a decent experience in mobile, where I could not find a way to put the canvas panning to work (so, when a node label partially disappeared, I had no way to select that node and centre the whole tree by consequence, to allow the further exploration of other nodes...).
What I did was change the function fitsInCanvas:
fitsInCanvas: function(pos, canvas, nodeW, nodeH) {
var size = canvas.getSize();
if(pos.x >= size.width || (pos.x + nodeW) < 0
|| pos.y >= size.height || pos.y + nodeH < 0) return false;
return true;
}
And called it accordingly on placeLabel:
placeLabel: function(tag, node, controller) {
...
...
...
var style = tag.style;
style.left = labelPos.x + 'px';
style.top = labelPos.y + 'px';
// Now passing on the node's width and heigh
style.display = this.fitsInCanvas(labelPos, canvas, w, h)? '' : 'none';
controller.onPlaceLabel(tag, node);
}
However, this is no solution.
You now will probably see your labels falling off the canvas, in a weird effect, until the whole node disappears.
And, obviously, I changed the source directly... a ticket should be filled on github.
EDIT:
Actually, it seems that I was working with an old version of the lib. The discussed behaviour changed to something similar to what I was describing. So, there is no need to change the code. Just download again your files. Specifically, the following link should give you these changes:
https://github.com/philogb/jit/blob/3d51899b51a17fa630e1af64d5393def589f874e/Jit/jit.js
There is a much simpler way to fix this although it might not be as elegant.
First, use the CSS 3 overflow attribute on the div associated with the Spacetree. For example, if the div in your HTML page that is being used by infovis is
<div id="infovis"> </div>
Then, you want some CSS that makes sure that your canvas does not allow overflow.
#infovis {
position:relative;
width:inherit;
height:inherit;
margin:auto;
overflow:hidden;
}
Next, in your your space tree definition, you probably have a placeLabel : function defined. At the end of it, simply set the style.display = "";. This force the label to be shown if the node is placed onto the canvas. For example:
onPlaceLabel: function(label, node, controllers){
//override label styles
var style = label.style;
if (node.selected) {
style.color = '#ccc';
}
else {
style.color = '#fff';
}
// show the label and let the canvas clip it
style.display = '';
}
Thus, you are displaying the text and turning it over to the browser to clip any part of the node or the label that extend off the canvas.
Related
I'm using d3 library to create a svg graphic. The problem I have is when I resize the window. The whole graphic resizes meaning that texts (legend and axis) resize as well, to the point where it's unreadable. I need it to keep the same size when resizing.
I've been searching online and I found this solution:
var resizeTracker;
// Counteracts all transforms applied above an element.
// Apply a translation to the element to have it remain at a local position
var unscale = function (el) {
var svg = el.ownerSVGElement;
var xf = el.scaleIndependentXForm;
if (!xf) {
// Keep a single transform matrix in the stack for fighting transformations
xf = el.scaleIndependentXForm = svg.createSVGTransform();
// Be sure to apply this transform after existing transforms (translate)
el.transform.baseVal.appendItem(xf);
}
var m = svg.getTransformToElement(el.parentNode);
m.e = m.f = 0; // Ignore (preserve) any translations done up to this point
xf.setMatrix(m);
};
[].forEach.call($("text"), unscale);
$(window).resize(function () {
if (resizeTracker) clearTimeout(resizeTracker);
resizeTracker = setTimeout(function () { [].forEach.call($("text"), unscale); }, 0);
});
And added it to my code, but it's not working. I debugged it and at this part of the code:
var xf = el.scaleIndependentXForm;
It always returns the same matrix: 1 0 0 1 0 0 and the text keeps resizing as does the rest of the svg elements instead of keeping static.
Could anyone help me, please?
Thanks in advance.
The same thing was happening to me with an SVG generated by SnapSVG until I noted that the example page on which this does work wraps its 'main' SVG tag in another SVG tag before using el.ownerSVGElement.ownerSVGElement rather than el.ownerSVGElement.
Wrapping my SVG in an 'empty' wrapper SVG (note style overflow:visible;) I had much better results!
Edit: oh, wait. Internet Explorer still isn't happy. Seems the author of the solution is aware...
I'm using jointjs to make diagrams which will be user-editable. The user may drag them around and relocate each cell. However, when a cell is dragged to the edge, it overflows and becomes cut off. I want to prevent this from happening, instead the cell to stop before it gets to the edge of the paper and not be allowed to cross the edge, thus always staying completely within the paper. The behavior can be seen in jointjs' very own demos here:
http://www.jointjs.com/tutorial/ports
Try dragging the cell to the edge and you'll see that it eventually becomes hidden as it crosses the edge of the paper element.
Secondly, I'm using the plugin for directed graph layout, found here:
http://jointjs.com/rappid/docs/layout/directedGraph
As you can see, the tree position automatically moves to the upper left of the paper element whenever your click layout. How can I modify these default positions? The only options I see for the provided function are space between ranks and space between nodes, no initial position. Say I wanted the tree to appear in the middle of the paper upon clicking 'layout', where would I have to make changes? Thanks in advance for any help.
As an addition to Roman's answer, restrictTranslate can also be configured as true to restrict movement of elements to the boundary of the paper area.
Example:
var paper = new joint.dia.Paper({
el: $('#paper'),
width: 600,
height: 400,
model: graph,
restrictTranslate: true
})
I. To prevent elements from overflowing the paper you might use restrictTranslate paper option (JointJS v0.9.7+).
paper.options.restrictTranslate = function(cellView) {
// move element inside the bounding box of the paper element only
return cellView.paper.getArea();
}
http://jointjs.com/api#joint.dia.Paper:options
II. Use marginX and marginY DirectedGraph layout options to move the left-top corner of the resulting graph i.e. add margin to the left and top.
http://jointjs.com/rappid/docs/layout/directedGraph#configuration
I think my previous answer is still feasible, but this is how I implemented it in my project. It has an advantage over the other answer in that it doesn't require you to use a custom elementView and seems simpler (to me).
(Working jsfiddle: http://jsfiddle.net/pL68gs2m/2/)
On the paper, handle the cell:pointermove event. In the event handler, work out the bounding box of the cellView on which the event was triggered and use that to constrain the movement.
var graph = new joint.dia.Graph;
var width = 400;
var height = 400;
var gridSize = 1;
var paper = new joint.dia.Paper({
el: $('#paper'),
width: width,
height: height,
model: graph,
gridSize: gridSize
});
paper.on('cell:pointermove', function (cellView, evt, x, y) {
var bbox = cellView.getBBox();
var constrained = false;
var constrainedX = x;
if (bbox.x <= 0) { constrainedX = x + gridSize; constrained = true }
if (bbox.x + bbox.width >= width) { constrainedX = x - gridSize; constrained = true }
var constrainedY = y;
if (bbox.y <= 0) { constrainedY = y + gridSize; constrained = true }
if (bbox.y + bbox.height >= height) { constrainedY = y - gridSize; constrained = true }
//if you fire the event all the time you get a stack overflow
if (constrained) { cellView.pointermove(evt, constrainedX, constrainedY) }
});
Edit: I think this approach is still feasible,but I now think my other answer is simpler/better.
The JointJS docs provide a sample where the movement of a shape is contrained to lie on an ellipse:
http://www.jointjs.com/tutorial/constraint-move-to-circle
It works by
Defining a new view for your element, extending joint.dia.ElementView
Overiding the pointerdown and pointermove event in the view to implement the constraint. This is done by calculating a new position, based on the mouse position and the constraint, and then passing this to the base ElementView event handler
Forcing the paper to use your custom element view
This approach can be easily adapted to prevent a shape being dragged off the edge of your paper. In step 2, instead of calculating the intersection with the ellipse as in the tutorial, you would use Math.min() or Math.max() to calculate a new position.
I have two canvases. I have made them circular using border-radius. The 2nd is positioned inside the first one (using absolute position).
I have click events on both circles. If you click on inside canvas, the color at the point of the click is loaded in the outside canvas with opacity varying from white to the picked color and finally to black. If you click on outer canvas the exact color value at that point is loaded in the text-box at the bottom
I am unable to click in red zones (as shown in figure below) of the outer canvas when using chrome. I tried z-idex, arcs but nothing is helping me. But In Firefox everything is working fine.
Note: You can drag the picker object in the outer circle. But if you leave it in red zones, you would not be able to click it again in Chrome. Clicking in green zone will get you its control again
Code in this JSFiddle
Edit
I excluded all irrelevant code to make it easy. Now there is only a container having two canvas.
Filled simply with two distinct colors. Open following fiddle link in both chrome and firefox. Click on both cirles in different zones and see difference in chrome and firefox. I want them to behave in chrome as they do in firefox
Note I will ultimately draw an image in inner canvas.
Updated Fiddle Link
-
Your problem is because canvases currently are always rectangular, even if they don't look rectangular. Border radius makes the edges except the circle transparent, but it still doesn't stop events in Chrome on the corner areas. This is why you cannot click the bottom circle in those areas
I even tried putting it inside of a container that had a border-radius instead but the click event still goes through
With that being said, you have two options. You could either change your code to only use one canvas with the same type of layout, just drawing the background circle before the other each time. Essentially you'd draw a circle, draw your black to color to white gradient, use the xor operation to combine the two into one circle, then do the same with the rainbox gradient. You must draw the background circle first because canvas paints over the old layers every time
or
You could use javascript to only detect clicks in the circular area which takes just a little bit of math (: This solution is featured in edit below
In the future, CSS Shapes may allow canvases to be non-rectangular elements to be used, I'm actually not sure, but we don't have that capability yet at least
Edit
Alright, so after going through your code a bit it seems there are some things I should cover before I offer a solution
Setup all your finite variables outside of the functions that run every time. This means you don't put them (like radiuses, offsets, etc.) in the click function or something that runs often since they don't change
Your "radius"es are actually "diameter"s. The format of .rect goes .rect(x, y, width (diameter of circle), height (diameter of circle))
Almost always when overlaying canvases like you are you want to make them equal dimensions and starting position to prevent calculation error. In the end it makes it easier, doing all relative positioning with javascript instead of mixing it with CSS. In this case, however, since you're using border-radius instead of arc to make a circle, keep it like it is but position it using javascript ....
jQuery isn't needed for something this simple. If you're worried about any load speed I'd recommend doing it in vanilla javascript, essentially just changing the .click() functions into .onclick functions, but I left jQuery for now
You can declare multiple variables in a row without declaring var each time by using the following format:
var name1 = value1,
name2 = value2;
Variables with the same value you can declare like so:
var name1 = name2 = sameValue;
When children have position:absolute and you want it to be positioned relative to the parent, the parent can have position:relative, position:fixed, or position:absolute. I would think you'd want position:relative in this case
When you don't declare var for a variable it becomes global (unlessed chained with a comma like above). For more on that read this question
Now, onto the solution.
After talking with a friend I realized I could sort do the math calculation a lot easier than I originally thought. We can just calculate the center of the circles and use their radiuses and some if statements to make sure the clicks are in the bounds.
Here's the demo
After everything is set up correctly, you can use the following to detect whether or not it's in the bounds of each
function clickHandler(e, r) {
var ex = e.pageX,
ey = e.pageY,
// Distance from click to center
l = Math.sqrt(Math.pow(cx - ex, 2) + Math.pow(cy - ey, 2));
if(l > r) { // If the distance is greater than the radius
if(r === LARGE_RADIUS) { // Outside of the large
// Do nothing
} else { // The corner area you were having a problem with
clickHandler(e, LARGE_RADIUS);
}
} else {
if(r === LARGE_RADIUS) { // Inside the large cirle
alert('Outer canvas clicked x:' + ex + ',y:' + ey);
} else { // Inside the small circle
alert('Inner canvas clicked x:' + ex + ',y:' + ey);
}
}
}
// Just call the function with the appropriate radius on click
$(img_canvas).click(function(e) { clickHandler(e, SMALL_RADIUS); });
$(wheel_canvas).click(function(e) { clickHandler(e, LARGE_RADIUS); });
Hopefully the comments above and code make enough sense, I tried to clean it up as best as I could. If you have any questions don't hesitate to ask!
I have an inner div inside an outer div. The inner div is draggable and outer is rotated through 40 degree. This is a test case. In an actual case it could be any angle. There is another div called point which is positioned as shown in the figure. ( I am from a flash background . In Flash if I were to drag the inner div it would follow the mouse even if its contained inside an outer rotated div.) But in HTML the inner div does not follow the mouse as it can be seen from the fiddle. I want the div 'point' to exactly follow the mouse. Is this possible. I tried to work it using trignometry but could not get it to work.
http://jsfiddle.net/bobbyfrancisjoseph/kB4ra/8/
Here is my approach to this problem.
http://jsfiddle.net/2X9sT/21/
I put the point outside the rotated div. That way I'm assured that the drag event will produce a normal behavior (no jumping in weird directions). I use the draggable handler to attach the point to the mouse cursor.
In the drag event, I transform the drag offset to reflect the new values. This is done by rotating the offset around the outer div center in the opposite direction of the rotation angle.
I tested it and it seems to be working in IE9, Firefox, and Chrome.
You can try different values for angle and it should work fine.
I also modified the HTML so it is possible to apply the same logic to multiple divs in the page.
Edit:
I updated the script to account for containment behavior as well as cascading rotations as suggested in the comments.
I'm also expirementing with making the outer div draggable inside another div. Right now it is almost working. I just need to be able to update the center of the dragged div to fix the dragging behavior.
Try Dragging the red div.
http://jsfiddle.net/mohdali/kETcE/39/
I am at work now, so I can't do the job for you, but I can explain the mathematics behind the neatest way of solving your problem (likely not the easiest solution, but unlike some of the other hacks it's a lot more flexible once you get it implemented).
First of all you must realize that the rotation plugin you are using is applying a transformation to your element (transform: rotate(30deg)), which in turn is changed into a matrix by your browser (matrix(0.8660254037844387, 0.49999999999999994, -0.49999999999999994, 0.8660254037844387, 0, 0)).
Secondly it is necessary to understand that by rotating an element the axis of the child elements are rotate absolutely and entirely with it (after looking for a long time there isn't any real trick to bypass this, which makes sense), thus the only way would be to take the child out of the parent as some of the other answers suggest, but I am assuming this isn't an option in your application.
Now, what we thus need to do is cancel out the original matrix of the parent, which is a two step process. First we need to find the matrix using code along the following lines:
var styles = window.getComputedStyle(el, null);
var matrix = styles.getPropertyValue("-webkit-transform") ||
styles.getPropertyValue("-moz-transform") ||
styles.getPropertyValue("-ms-transform") ||
styles.getPropertyValue("-o-transform") ||
styles.getPropertyValue("transform");
Next the matrix will be a string as shown above which you would need to parse to an array with which you can work (there are jquery plugins to do that). Once you have done that you will need to take the inverse of the matrix (which boils down to rotate(-30deg) in your example) which can be done using for example this library (or your math book :P).
Lastly you would need to do the inverse matrix times (use the matrix library I mentioned previously) a translation matrix (use this tool to figure out how those look (translations are movements along the x and y axis, a bit like left and top on a relatively positioned element, but hardware accelerated and part of the matrix transform css property)) which will give you a new matrix which you can apply to your child element giving you the a translation on the same axis as your parent element.
Now, you could greatly simplify this by doing this with left, top and manual trigonometry1 for specifically rotations only (bypassing the entire need for inverse matrices or even matrices entirely), but this has the distinct disadvantage that it will only work for normal rotations and will need to be changed depending on each specific situation it's used in.
Oh and, if you are now thinking that flash was a lot easier, believe me, the way the axis are rotated in HTML/CSS make a lot of sense and if you want flash like behavior use this library.
1 This is what Mohamed Ali is doing in his answer for example (the transformOffset function in his jsFiddle).
Disclaimer, it has been awhile since I have been doing this stuff and my understanding of matrices has never been extremely good, so if you see any mistakes, please do point them out/fix them.
For Webkit only, the webkitConvertPointFromPageToNode function handles the missing behavior:
var point = webkitConvertPointFromPageToNode(
document.getElementById("outer"),
new WebKitPoint(event.pageX, event.pageY)
);
jsFiddle: http://jsfiddle.net/kB4ra/108/
To cover other browsers as well, you can use the method described in this StackOverflow answer: https://stackoverflow.com/a/6994825/638544
function coords(event, element) {
function a(width) {
var l = 0, r = 200;
while (r - l > 0.0001) {
var mid = (r + l) / 2;
var a = document.createElement('div');
a.style.cssText = 'position: absolute;left:0;top:0;background: red;z-index: 1000;';
a.style[width ? 'width' : 'height'] = mid.toFixed(3) + '%';
a.style[width ? 'height' : 'width'] = '100%';
element.appendChild(a);
var x = document.elementFromPoint(event.clientX, event.clientY);
element.removeChild(a);
if (x === a) {
r = mid;
} else {
if (r === 200) {
return null;
}
l = mid;
}
}
return mid;
}
var l = a(true),
r = a(false);
return (l && r) ? {
x: l,
y: r
} : null;
}
This has the disadvantage of not working when the mouse is outside of the target element, but it should be possible to extend the area it covers by an arbitrary amount (though it would be rather hard to guarantee that it covers the entire window no matter how large).
jsFiddle: http://jsfiddle.net/kB4ra/122/
This can be extended to apply to #point by adding a mousemove event:
$('#outer').mousemove(function(event){
var point = convertCoordinates(event, $("#outer"));
$("#point").css({left: point.x+1, top: point.y+1});
});
Note that I adjust the x and y coordinates of #point by 1px to prevent it from being directly underneath the mouse; if I didn't do that, then it would block dragging #inner. An alternative fix would be to add handlers to #point that detect mouse events and pass them on to whichever element is directly underneath #point (and stopPropagation, so that they don't run twice on larger page elements).
jsFiddle: http://jsfiddle.net/kB4ra/123/
It seems to me that if you do not rotate the div, the div exactly follows the mouse.
This might be a problem with the plugin..maybe you could simulate the draggable function corretly?
This basically will do what you need though it is buggy. Bind the drag event handler, intercept the ui object and modify it to use the offset X and Y of the parent element. All of the X, Y, top, left etc. are in those objects. I will try to get you a better example sometime when today when I get a bit more time. Good luck!
http://jsfiddle.net/kB4ra/107/
may be this is issue of your jquery library or you can check this by assigning z-order value of inner div and outer div make sure that you give higher number to inner div.
Is there any accurate way to get the real size of a svg element that includes stroke, filters or other elements contributing to the element's real size from within Javascript?
I have tried pretty much everything coming to my mind and now I feel I'm coming to a dead end :-(
Updated question to add more context (Javascript)
You can't get the values directly. However, you can get the dimensions of the bounding rectangle:
var el = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle
console.log( rect.width );
console.log( rect.height);
It is supported at least in the actual versions of all major browser.
Check fiddle
Both raphael js http://dmitrybaranovskiy.github.io/raphael/ and d3 js http://d3js.org/ have various methods to find the size of an svg object or sets of svg object. It depends on if it's a circle, square, path, etc... as to which method to use.
I suspect you are using complex shapes, so in that case bounding box would be your best bet http://raphaeljs.com/reference.html#Element.getBBox
(Edit: updated reference site.) http://dmitrybaranovskiy.github.io/raphael/reference.html#Element.getBBox
Here is an example using D3.js:
Starting with a div:
<div style="border:1px solid lightgray;"></div>
The javascript code looks like this:
var myDiv = d3.select('div');
var mySvg = myDiv.append('svg');
var myPath = mySvg.append('path');
myPath.attr({
'fill': '#F7931E',
'd': 'M37,17v15H14V17H37z M50,0H0v50h50V0z'
});
// Get height and width.
console.log(myPath.node().getBBox());
If it is an SVG used as a CSS background image and you're using React you can use background-image-size-hook.
import { useBackgroundImageSize } from 'background-image-size-hook'
const App = () => {
const [ref, svg] = useBackgroundImageSize()
console.log(svg) // { width, height, src }
return <SVGBackgroundImageComponent ref={ref} />
}
You didn't specify any programming language. So I can suggest to use Inkscape.
In the file menu you find document's properties and in the first page there's "resize page to content" command. In this way you remove all the white space around your draw and you see the real size. After width and height values apprear inside the header of svg.
I know that Inkscape supports scripting and command line operations but I don't know if it's possible to do the trimming operatation in this way. But if it's possible you can do that from every programming language.