Snapsvg - get height and width of text element - svg

I am altering the elements contents using
svgTextLines[name].node.innerHTML = line.val();
svgTextLines[name].node.textContent = line.val();
and trying to get the height and width of the element after the content has changed but I cant seem to find any property in the elemement.node object that gets updated. As the element has not transformed I can understand why but is there a way I can get this information?
Regards

I'm using SnapSVG and I had the same problem.
You can use getBoundingClientRect to get an object with this parameter.
var s = Snap("#svg");
Snap.load("mascot.svg", function (f) {
s.append(f);
var rect = s.searchAll("g")[0];
var dimens = rect.node.getBoundingClientRect();
console.log(dimens.width)
});

Related

RaphaelJS color the tip of a path

Does anyone know if it's possible to change, say, the last 10 pixels of a path to be a different color? I tried doing it with gradients, and that didn't work. There doesn't seem to be any other way that I can find to do it either. Any help would be greatly appreciated.
You should be able to do this with Raphael's element.getSubpath() interface.
Subpath allows you to get a 'path of a path' between certain points. So, if you have a path already, like
var mainPath = paper.path("M10,10R20,70 30,40 40,80 50,10 60,50 70,20 80,30 90,90");
You can get a subpath which gives you a 'slice' of that path with arbitrary start and end points:
var subpathString = mainpath.getSubpath(20, 50);
And then you can create a new element using that path with, say, a different stroke width:
var subpath = paper.path(subpathString);
subpath.attr({'stroke-width' : 4});
This will then look like this jsFiddle: http://jsfiddle.net/1ndmz3d6/3/
To make the last 10 pixels of your path red, for instance, you just need to know the length of your path. With element.getTotalLength(), that's easy:
var pathLength = mainPath.getTotalLength();
var subpathStart = pathLength - 10;
var subpathString = mainPath.getSubpath(subpathStart, pathLength);
var highlightedPathSegment = paper.path(subpathString);
highlightedPathSegment.attr({'stroke-width' : 2, stroke : '#FF0000'});
And there you should have it: http://jsfiddle.net/1ndmz3d6/5/

how to get text bounding box in famo.us

I am attempting to draw an SVG bezier curve that starts at the end of a text string that is in a Surface. I can set the size of the Surface to [true, true], which is supposed to make the size equal the text bounding box. But if I later try "mySurface.size[0]" in order to get the width, it returns "true"! I need to get a number for the width and height of that bounding box, in order to calculate the end point of my bezier curve! The equivalent DOM approach would just be to use the .getBBox() function.. how do I do this in Famo.us?
this is maybe because the surface hasn't rendered yet. there are a few similar questions here, one of them from me:
how can we get the size of a surface within famo.us?
you could also try deferring or using a setTimeout or Engine.nextTick() to check the size on the next loop through.
if you find an elegant solution let us know as this is a big problem in many places using famous - having to do multiple highjinks where you can't really position a scene on the initial setup - you have to let it render and then adjust...
You can use the 'getSize' function and specify 'true' to get the real size of the surface:
var realSize = surface.getSize(true);
#ljzerenHein, thanks for the hint.. unfortunately, surface.getSize(true) returns null!
#dcsan, thanks for the link. I believe you may be right, however the solution linked to ends up being much too involved for me.
After much searching, hacking, and experimenting, I've settled on the following approach:
-] use the DOM to get untransformed bounding boxes for text strings
-] format the text strings in SVG form
-] make it so the strings are invisible (set fill and stroke to none)
-] reuse the same "div" element for all the strings that I want to measure
-] once I have the untransformed bounding box, then set the famous surface size to that and then apply modifiers.
-] if I need the bounding box after all transforms have been applied, then get the total accumulated transforms for the surface and multiply that with the original untransformed bounding box
Here's the code to create the DOM element, insert SVG text, then get the bounding box:
//Do this part once, of creating a DOM element and adding it to the document
var el1 = document.createElement("div");
document.body.appendChild(el1); //only need to append once -- just set innerHTML after
//now set the SVG text string -- from this point down can be repeated for multiple
// strings without removing or re-adding the element, nor fiddling with the DOM
var text1_1_1_SVG = '<svg> <text x="0" y="0" style="font-family: Arial; font-size: 12;fill:none;stroke:none" id="svgText1">' + myFamousSurface.content + '</text> </svg>';
//note the id is inside the text element! Also the fill and stroke are null so nothing paints
el1.innerHTML = text1_1_1_SVG;
//now get the element -- this seems to be what triggers the bounding box calc
var test = document.getElementById("svgText1"); //this is ID in the text element
//get the box, take the values out of it, and display them
var rect = test.getBoundingClientRect();
var str = "";
for (i in rect) { //a trick for getting all the attributes of the object
str += i + " = " + rect[i] + " ";
}
console.log("svgText1: " + str);
FYI, all of the SVGTextElement methods seem to be callable upon gotElem.
SVGTextElement docs here: http://msdn.microsoft.com/en-us/library/ie/ff972126(v=vs.85).aspx
#seanhalle
I'm pretty sure .getSize(true) is returning null because the element has not yet been added to the DOM. Keep in mind that famo.us is synchronized with animation-frames, and updates to the DOM happen don't happen instantly. Accesssing the DOM directly (aka pinging) is strongly disadviced because you will loose the performance benefits that famo.us promises.
What I would do is create a custom view to wrap your surface inside and implement a render-method in it. In the render-method, use getSize(true) to get the size. If it returns null,
you know it has not yet been committed to the DOM.
view in action as jsfiddle
define('MyView', function (require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
function MyView() {
View.apply(this, arguments);
this.surface = new Surface();
this.add(this.surface);
}
MyView.prototype = Object.create(View.prototype);
MyView.prototype.constructor = MyView;
MyView.prototype.render = function() {
var size = this.getSize(true);
if (size) {
if (!this.hasSize) {
this.hasSize = true;
console.log('now we have a size: ' + size);
}
this.surface.setContent('Size: ' + JSON.stringify(size));
} else {
console.log('no size yet');
}
return this._node.render();
};
module.exports = MyView;
});

How to right/end align text along an textPath inside an arc using d3.js?

Here's the fiddle: http://jsfiddle.net/DevChefOwen/CZ6Dp/
var text = g.append("text")
.style("font-size",30)
.style("fill","#000")
.attr("dy",0)
.append("textPath")
.attr("xlink:href","#yyy")
.style("text-anchor","left") // using "end", the entire text disappears
.text("some text");
I've tried a number of different things to no avail. The left align is the easy part. If you did a middle, though, you see only "text" instead of "some text", implying that "some" is just hidden because it went "out of span" for the given arc.
If, however, I added:
.attr("startOffset","39%")
(as in here: http://jsfiddle.net/DevChefOwen/2H99c/)
It would look right aligned, but outside of programmatically trying to get the width/height of the text element and look for sharp changes in width/height (which seems wrong and likely error-prone), I can't seem to find a way to right align the text.
I've also tried using an SVG path (essentially a curved arc line) and the same disappearing act happens with the text when "text-anchor" is set to "left".
Thanks ahead for your time!
The question is somewhat confusing matters. The issue isn't aligning text at the end of the path -- that's easy to do with "text-anchor"="end" and "startOffset"="100%".
However, using those settings with the path created by the d3 arc function, you end up with the text cornering around the end of the inside curve and the left straight edge, to the end of the path as defined by the arc function:
http://jsfiddle.net/CZ6Dp/8/
The real issue is that the path that you want the text to be aligned along (the outside arc of the shape) is only one segment of the path that defines the shape.
(By the way, "left" and "right" are not valid values for the "text-anchor" property, and will just be ignored).
The answer by #defghi1977 gives one way to approach the problem, by figuring out the length of the path segment that you do want to use and adjusting the start offset accordingly.
Another way to approach the problem is to create a separate path (not drawn on screen) that represents only the part of the path that you want to be used for positioning text.
There are a number of possible ways to create a path that only represents the outside arc (some example code here). #defghi1977's approach of grabbing it from the existing path with regular expressions is probably the most efficent for your situation. But instead of just creating a temporary element to calculate a length, I actually have to add the new path to the DOM so it can be used as the reference path for the <textPath> element. (Which I suppose is the downside to this approach -- twice as many DOM elements!)
var path = g.append("svg:path")
.attr("d", arct)
.style("fill","#ccc")
.attr("transform", "translate("+cfg.w/2+","+cfg.h/2+")")
.each(function(d,i) {
var justArc = /(^.+?)L/;
//grab everything up to the first Line statement
var thisSelected = d3.select(this);
var arcD = justArc.exec( thisSelected.attr("d") )[1];
defs.append("path")
.attr("id", "yyy") //normally the id would be based on the data or index
.attr("d", arcD)
.attr("transform", thisSelected.attr("transform") );
//if you can avoid using transforms directly on the path element,
//you'll save yourself having to repeat them for the text paths...
});
var text = g.append("text")
.style("font-size",30)
.style("fill","#000")
.attr("dy",0)
.append("textPath")
.attr("xlink:href","#yyy")
.style("text-anchor","end")
.attr("startOffset","100%")
.text("some text");
http://jsfiddle.net/CZ6Dp/9/
Again, factoring in the extra DOM load #defghi1977's method is probably slightly preferrable, although this version has the benefit of not being dependent on browser support for getTotalLength. But as far as I know that method is fairly well implemented.
So just consider this an alternate approach for completeness' sake.
This path is constructed by 4(or 5) path segments.
So, this probrem will be solved to get first arc path length.
But I don't know how to get sub path length by using d3.js, thus I use svgdom directly.
I tried to fix your code. If this code is not what you hope, I'm sorry.
path-anchor attribute to end.
define function to get startOffset value.
var path = g.append("svg:path")
.attr("id","yyy")
.attr("d", arct)
.style("fill","#ccc")
.attr("transform", "translate("+cfg.w/2+","+cfg.h/2+")");
var text = g.append("text")
.style("font-size",30)
.style("fill","#000")
.attr("dy",0)
.append("textPath")
.attr("xlink:href","#yyy")
//.style("text-anchor","left") // using "end", the entire text disappears
.attr("text-anchor", "end")
.text("some text")
.attr("startOffset",function(){
var d = document.getElementById("yyy").getAttribute("d");
var tmp = document.createElementNS("http://www.w3.org/2000/svg" ,"path");
//get the arc segment of path
var arc = d.match(/(^.+?)L/)[1];
tmp.setAttribute("d", arc);
//return offset position
return tmp.getTotalLength();
});
I think the confusion comes from the meaning of text-anchor - it's not "relative to where on the parent will I justify" but rather "what part of me should I align to the start".
You're right to try to use startOffset to move the origin. Since the outer radius of your path is longer than the inner radius, the correct start offset is a little more than half of the path (around 53%).
Just a little more twiddling with your settings and you should have it. Here's a fiddle with my interpretation of what you're looking for.

Integrating Poilu raphael boolean operations(union,substraction) with SVG-edit

I am doing a modification of svg-edit, more specifically Mark McKays Method draw: https://github.com/duopixel/Method-Draw.
I want to use this Raphael library i found: https://github.com/poilu/raphael-boolean that allows me to perform boolean(set) operations on paths within my canvas.
Now i have implemented a button within the editor that fires up a function:
var paper = Raphael("canvas", 250, 250);
var path = paper.path("M 43,53 183,85 C 194,113 179,136 167,161 122,159 98,195 70,188 z");
path.attr({fill: "#a00", stroke: "none"});
var ellipse = paper.ellipse(170, 160, 40, 35);
ellipse.attr({fill: "#0a0", stroke: "none"});
var newPathStr = paper.union(path, ellipse);
//draw a new path element using that string
var newPath = paper.path(newPathStr);
newPath.attr({fill: "#666"});
// as they aren't needed anymore remove the other elements
path.remove();
ellipse.remove();
Okay, upon clicking the button isnt the editor supposed to return a unioned(welded) path with an ellipse?
or am i getting this wrong?
i am figuring that something must change with the var paper = Raphael("canvas", 250, 250); line since svg-edit is using a different name for the canvas but i have no idea how to go about it.
Any help will be deeply appreciated as i have been struggling for sometime with this.
UPDATE: This library is unable to handle multi-object welding, self intersections and many other cases. It is only working if we want to perform operations on 2 simple objects. This might not be immediately relevant to the question at hand but i thought it is wise to mention it anyway.
Refer to this question if you are looking for Boolean Operations on SVG elements: Boolean Operations on SVG paths
The code you posted works in isolation, as shown here: http://jsfiddle.net/5SaR3/
You should be able to change the Raphael constructor line to something like:
var paper = Raphael(canvas);
where canvas is an object reference to the SVG element used by svg-edit.

Label does not render the string "0" (Flex 4.5)

I was writing a custom chart component where. To add labels, I create a spark label and add it on screen. Although all other labels rendered, I noticed that the zero label does not render at all. Here's my code:
var invisibleTextField:TextField = new TextField();
var zeroLabel:spark.components.Label = new spark.components.Label();
zeroLabel.text = "0";
zeroLabel.name = "0Label";
invisibleTextField.text = " 0 ";
zeroLabel.width = invisibleTextField.textWidth;
zeroLabel.height = invisibleTextField.textHeight;
addChild(zeroLabel);
After multiple attempts, I figure that the label discards "0" as an empty string. I managed to workaround using spaces before and after the zero. Only one space would also do, but I needed center aligning. Anyone has any idea why this happens?
There's a delay between text is filled into a text field and when it's dimensions are updated. Try using TextExtent instead of an invisible text field to do what you're doing.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/TextExtent.html

Resources