SVG Animation Jumping - javascript

I'm beginning to just learn some SVG (and javascript, I suppose), and I'm having a hard time understanding why this is not flowing smoothly. The 0 moves a small amount (presumably "1" horizontally on the x axis), but than begins to leap in great bounds. Is this because the browser I am using (Chrome) is refreshing/redrawing at a much longer pace? Any input would be greatly appreciated.
<svg width="100%" height="100%"
xmlns="http://www.w3.org/2000/svg" version="1.1"
xmlns:xlink="http://www.w3.org/1999/xlink"
onload="startup(evt)">
<script>
function startup(evt){
svgDoc=evt.target.ownerDocument;
setInterval(function(){
e=svgDoc.getElementById("zero");
var x = e.getAttribute("x");
e.setAttribute("x",x+1);
},1000);
}
</script>
<defs>
<text id="zero">0</text>
</defs>
<use x="40" y="20" xlink:href="#zero"/>
</svg>

You have to make sure you're working with numbers and not strings:
var x = +(e.getAttribute("x"));
e.setAttribute("x",x+1);
JavaScript prefers string "addition" to numeric, so when "x" is a string, x+1 means "add the character '1' to the end of the string x". By forcing the return value from .getAttribute() to numeric via the unary "+" operator, you avoid that problem.
(There are various ways to force a string to be converted to a number. Pick your favorite :-)

Related

Making svg path with rounded edge responsive

I am working on a svg graphic that will represent health bar in a game, thus far it is looking like this https://jsfiddle.net/8ds9hpuv
Concept is to have responsive bar that decreases / increases in width based on character health.
Right now I can't figure out how to decrease this path in width, but maintain that rounded edge on the right side all the time.
Ideally I would like to make it's height responsive as well
<svg width="428" height="35">
<path d="M0 0h414.333785C423.444595 9.346449 428 15.179782 428 17.5c0 2.320218-4.555405 8.153551-13.666215 17.5H0V0z" fill="red"/>
</svg>
I've modified the path by changing every command to lowercase (using this tool: Convert SVG path to all-relative or all-absolute ) but I've left the last H command to uppercase since H0 is going back to x="0"
Next I'm replacing the first h command with the variable healthIndicator
I'm assuming that the tip of the arrow has only an aesthetical function.
For the sake of the demp I'm using an input type range to change the value of the healthIndicator. I hope this is what you need.
itr.addEventListener("input",()=>{
let healthIndicator = itr.value;
let d = `M0,0 h${healthIndicator}c9.111,9.346,13.666,15.18,13.666,17.5c0,2.320218,-4.555405,8.153551,-13.666215,17.5H0v-35z`;
thePath.setAttributeNS(null,"d", d);
})
svg{border:1px solid}
<svg viewBox="0 0 550 35" >
<path id="thePath" d="M0,0
h414
c9.111,9.346,13.666,15.18,13.666,17.5
c0,2.320218,-4.555405,8.153551,-13.666215,17.5
H0z" fill="red"/>
</svg>
<input type="range" id="itr" value="414" min="0" max="500" />

Stretching path based on character positions in text element

I'm writing a document in HTML5 with included SVG (actually ePub3), and I wanted to have a path in the SVG going from one character position in a text element to another. I found a way to do it, but it seems like a particularly awkward way, and I am wondering if anyone has any tips for improving it.
A bit more context: the particular illustration is to demonstrate how multiplication by integer powers of 10 shifts the decimal point around in decimal representations of numbers (particularly for converting between percentages and decimal representations, multiplying or dividing by 100). So I want the decimal number in a text element, and an arrow (specified as a path element with an arrowhead marker on one end) under it showing the shift of the decimal point from one position to another. But I want to do in in a general enough way that the arrow stretches for me if I need to change the font size or add digits between the start and stop positions of the arrow.
Here is what I came up with:
<svg id="shift" height="40" width="85">
<defs>
<marker id="arrowhead" markerWidth="6" markerHeight="6" refX="3" refY="0" >
<path d="M 0 6 L 3 0 6 6" stroke="black" fill-opacity="0" rotate="90"/></marker>
</defs>
<text id="fullstring" x="0" y="15" fill="black" font-family="serif" font-size="100%">10<!--
--><tspan id="firstdec" fill="blue">.</tspan>0000<tspan id="seconddec" fill="red">.</tspan>00</text>
<path id="decarrow" stroke="black" fill="white" stroke-width="1" d=""
style="marker-end: url(#arrowhead);"/>
<script type="text/javascript"><![CDATA[
var arrowpath = document.getElementById("decarrow");
var firstdecbox = document.getElementById("firstdec").getExtentOfChar(0);
document.getElementById("fullstring").setAttribute("y",""+firstdecbox.height);
document.getElementById("shift").setAttribute("height",""+(1.4*firstdecbox.height+15));
document.getElementById("shift").setAttribute("width", ""+document.getElementById("fullstring").getComputedTextLength());
var seconddecbox = document.getElementById("seconddec").getExtentOfChar(0);
var startx = firstdecbox.x+firstdecbox.width/2;
var starty = firstdecbox.y+firstdecbox.height;
var stopx = seconddecbox.x+seconddecbox.width/2;
var stopy = seconddecbox.y+seconddecbox.height;
var bendheight = 15;
arrowpath.setAttribute("d", "M "+startx+" "+starty+" L "+ startx+" "+(starty+bendheight)+" "+stopx+" "+(stopy+bendheight)+" "+stopx+" "+stopy);
]]></script>
</svg>
I can't help thinking that there must be a better way to do this. What I really want is a way to specify a path with starting point and ending point based on character positions in a text element. Is there such a way to specify path data relative to character positions? Or have I really stumbled my way onto the best available option?

How can I dynamically update the patternTransform attribute for an SVG text

I have a simple text filled with a pattern like:
<svg>
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="690" height="200" patternTransform="translate(0,0) scale(1,1)">
<image xlink:href="http://lorempixel.com/690/200/" width="690" height="200"/>
</pattern>
</defs>
<text id='text1' y='200' fill='url(#img1)'>Hello</text>
</svg>
However I would like to dynamically update the pattern position through javascript.
I have tried to update through:
document.getElementById('img1').setAttribute('patternTransform', 'translate(0,200) scale(1,1)')
But it didn't work.
Your image seems to be a random bitmap which is 690 pixels wide and crucially 200 pixels high. When you change the pattern by calling this:
document.getElementById('img1').setAttribute('patternTransform', 'translate(0,200) scale(1,1)')
You move the pattern down by 200 pixels and patterns wrap around. Since this pattern is 200 pixels high, it wraps around so it looks exactly the same as it did before, like a runner in a race doing exactly one more lap looks like he's in the same position. Try using some other number than 200 and you'll see that the pattern does change.
Try this
$('#img1')[0].setAttribute('patternTransform', 'translate(0,200) scale(1,1)');
or
$('#img1').first().setAttribute('patternTransform', 'translate(0,200) scale(1,1)');

SVG Scaling and Coordinates

This is my first SVG project, and I’m not a programmer, but I dabble in interactive infographics. My previous experience in this area comes from working with ActionScript.
I’m using plain SVG (no Raphael, D3, etc.) and trying to create an interactive barchart. After some initial difficulty with the SVG coordinate system and scaling, I found some code online that handles the postscaling translation:
<text x="x_coord0" y="y_coord0" transform="scale(x_scale, y_scale) translate(-x_coord0*(x_scale-1)/x_scale, -y_coord0*(y_scale-1)/y_scale)" …>text</text>
And I converted it into this JavaScript:
var translationfactor = ((0 - y_position)*(y_scalefactor - 1) / y_scalefactor);
var matrix = "scale(1," + y_scalefactor + ") translate(0," + Number(translationfactor) + ")";
targetbar.setAttribute("transform", matrix);
The problem is that I need the bars “translated” back to the chart’s baseline, not the original locations of their topmost points. Currently the correctly scaled bars are hugging the top of the chart:
http://billgregg.net/miscellany/upsidedown-barchart.png
I’ve tried several fixes, including plugging the bars’ ”missing height” into translationfactor (the bars start out the full height of the chart and get scaled down dynamically). Nothing has worked. Part of my problem is that, besides being new to SVGs, I can stare at that code all day and my brain still can’t parse it. Multiplying negative numbers is too abstract and at a fundamental level I just don’t “get” the math, which of course makes modifying the code difficult.
My questions:
(1) What’s the fix for the code above to position the bars back on the baseline of the chart?
(2) Is there a more transparent, more pedestrian way of accomplishing the translation? My first thought along these lines was that if a bar’s height is reduced to 40% of its original value, then multiplying the original Y coordinate value by 250% should reset the bar to its original location (at least its topmost point), but that doesn’t seem to work.
(3) Is there a way to set a bar’s point of origin to its bottom? In Flash it’s possible, though as far as I know it’s a manual, not a programmatic task.
(4) Is there a method similar to .localToGlobal() in ActionScript that would allow me to avoid having to mess with the local coordinate system at all?
Behind the scenes there is matrix math going on and it can be hard to get your head around the pre and post multiplication of arrays.
It's not entirely clear what you are trying to achieve, but reading between the lines, it sounds like you are wanting to provide graph coordinates in their raw(ish) form and have the SVG scale and position them for you(?)
If that's the case, then I think the solution is simpler than what you think.
Assuming I'm right, we'll start with something that looks like this:
<?xml version="1.0" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g transform="">
<rect x="0" width="1" height="5" fill="red"/>
<rect x="1" width="1" height="11" fill="green"/>
<rect x="2" width="1" height="12" fill="orange"/>
<rect x="3" width="1" height="8" fill="blue"/>
</g>
</svg>
Where x is obvious and the bar length is in height. y defaults to 0, so we don't need it here.
You basically want to know what goes in the transform to scale and position the bars on your page. The fact that your graph is "upside-down" helps a little. Because the origin in an SVG is at the top left.
First apply a scale. Let's make the bars 20 pixels wide, and scale the lengths up by 10.
<g transform="scale(20,10)">
Next you want to position the graph on the page. Let's put the top-left corner at (40,40).
In SVG the transformations are concatenated in order (post-multiplied) so in order for the translation to be what you specify and not be multiplied by the scale, you should put it first.
<g transform="translate(40,40) scale(20,10)">
So the final SVG looks like this:
<?xml version="1.0" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g transform="translate(40,40) scale(20,10)">
<rect x="0" width="1" height="5" fill="red"/>
<rect x="1" width="1" height="11" fill="green"/>
<rect x="2" width="1" height="12" fill="orange"/>
<rect x="3" width="1" height="8" fill="blue"/>
</g>
</svg>
The above has been simplified by assuming you have already subtracted the values from your base 20%. If you wanted to keep the pure raw values, it's possible, but things get a bit trickier. You would need to either tinker with both the y and height value of each bar, or use clipping to hide the part of the bar above 20%.
For "right way up"/normal graphs. All you need to do is make the y scale negative and translate the graph so that the bottom-left is where you want it.
<g transform="translate(40,140) scale(20,-10)">
Hope this helps.

Trying to create a re-usable text-box (text with a square background-colour) in SVG 1.1?

I'm trying to create (what I thought would be!) a simple re-usable bit of SVG to show three lines of text, with a background colour - to simulate a 'post-it' note.
I have found some useful code here to get the Bounds of the Text http://my.opera.com/MacDev_ed/blog/2009/01/21/getting-boundingbox-of-svg-elements which I am using.
So: I'm creating an group of text elements like this in the 'defs' section of my SVG:
<svg id="canvas" width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="post_it">
<text x="0" y="30" id="heading" class="heading">My Heading</text>
<text x="0" y="45" id="description" class="description">This will contain the description</text>
<text x="0" y="60" id="company" class="company">Very Big Company Ltd.</text>
</g>
And I'm displaying the text with a 'use' element like this:
<use id="12345" class="postit" xlink:href="#post_it" onclick="showId(this);"/>
I'm using the onclick to trigger a call to the following javascript function (defined in 'defs' section):
function showId(elem) {
post_it_rect=getBBoxAsRectElement(elem);
document.getElementById('canvas').appendChild(post_it_rect);
}
(The 'getBBoxAsRectElement(elem)' is from the link I posted).
As this stands; this works just fine - however if I change my 'use' element to position the text in a different place like this:
<use x="100" y="100" id="12345" class="postit" xlink:href="#post_it" onclick="showId(this);"/>
Now, the text displays in the correct place, but the resultant 'background-color' (actually a 'rect' element with opacity of 0.5) still shows on the top-left of the svg canvass - and the function used to calculate the rect is returning '-2' rather than '100' ('-98'?) as I need (I think).
What do I need to do to line up the 'rect' elements and the text elements ?
The author of the (very helpful article btw) script provides a more advanced script to draw a box round any 'bb' in an SVG, but I couldn't get this to work (missing 'transform' functions?).
I'm using Firefox 7.x to render the SVG ; and I'm loading a .svg file (ie, not embedded in html etc) straight from disk to test this).
Yes, you may need to compensate yourself for the x and y attributes on the <use> element for the time being, I'll try to find some time to update the blogpost and script.
Here's a draft SVG 1.1 test that among other things checks that the effect of the x and y attributes are included in the bbox. The line starting [myUse] is the one that tests this case, if it's red then that subtest failed. Chromium and Opera Next both pass that subtest, while Firefox nightly and IE9 doesn't. Note that the test itself has not gone through full review yet, and that it may still change.

Categories