I am relatively new in SVG drawing with HTML5.
What I want to do is to make a group of elements in SVG with g element so that all elements inside of that g element can work like a group and all the element's base x and y value can be received from the upper g element.
So, what I have done is something like this-
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
<g x="1000" y="1000">
<title>SVG Title Demo example</title>
<rect width="200" height="50"
style="fill:wheat; stroke:blue; stroke-width:1px"/>
<text style="text-anchor: middle;" class="small">My Text</text>
</g>
</svg>
What I expected is all the elements inside the g element will get x="1000" and y="1000" so my expected output is like this-
But I am getting this-
Re-
I don't like to set x and y element in text element. I just want to set relative x and y into the text element if needed, but that should be relative to g element.
Can anyone help me what I need to do to achieve my target with a group in SVG?
<g> elements don't support x or y attributes. You can use a transform instead though.
I've decreased the values from 1000 to 100 as otherwise the output is outside the 500 x 300 canvas of the outer <svg> element.
I've provided additional x and y attributes on the text element so it appears positioned as in your example. If wanted you could put the text itself in a <g> element or an <svg> element.
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
<g transform="translate(100, 100)">
<title>SVG Title Demo example</title>
<rect width="200" height="50"
style="fill:wheat; stroke:blue; stroke-width:1px"/>
<text x="100" y="30" style="text-anchor: middle;" class="small">My Text</text>
</g>
</svg>
or using an additional <g> element to avoid x and y on the text itself.
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
<g transform="translate(100, 100)">
<title>SVG Title Demo example</title>
<rect width="200" height="50"
style="fill:wheat; stroke:blue; stroke-width:1px"/>
<g transform="translate(100, 30)">
<text style="text-anchor: middle;" class="small">My Text</text>
</g>
</g>
</svg>
Alternatively you could use an inner <svg> element instead of a <g> element as that does support x and y attributes
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
<svg x="100" y="100">
<title>SVG Title Demo example</title>
<rect width="200" height="50"
style="fill:wheat; stroke:blue; stroke-width:1px"/>
<text x="100" y="30" style="text-anchor: middle;" class="small">My Text</text>
</svg>
</svg>
Related
Is it possible to set a background-image for an SVG <path> element?
For instance, if I set the element class="wall", the CSS style .wall {fill: red;} works, but .wall{background-image: url(wall.jpg)} does not, neither .wall {background-color: red;}.
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
Working example
Do you know how to sort SVG group elements by translate x value?
Here is the code:
<svg>
<g class="element" transform="translate(479, 247) scale(1)">...</g>
<g class="element" transform="translate(874, 145) scale(1)">...</g>
<g class="element" transform="translate(643, 356) scale(1)">...</g>
</svg>
As you can see x values of each element is 479,874, and 643.
I want to sort these 3 groups by that element's x value and append back to same SVG.
Expected Result:
<svg>
<g class="element" transform="translate(874, 145) scale(1)">...</g>
<g class="element" transform="translate(643, 356) scale(1)">...</g>
<g class="element" transform="translate(479, 247) scale(1)">...</g>
</svg>
You can use jQuery sort and some string parsing logic to retrieve your first parameter of translate:
function getValue(input){
return parseInt(input.outerHTML.substring(input.outerHTML.indexOf('(') + 1, input.outerHTML.indexOf(',')));
}
$('svg g').sort(function(a, b) {
return getValue(a) < getValue(b) ? 1 : -1;
}).appendTo('svg');
If you are interested in a slightly different way of doing it with lots of ES6 and functional ideas:
I modified the example a bit to show the order by the order in which the groups are painted on the SVG (in the order they appear in the DOM) by adding <text/> and <rect/> elements. So before it looks like this:
Then after it looks like this:
i.e. <g class="element" transform="translate(479, 247) scale(1)">...</g> is painted last because it is the last child of the <svg/> tag.
Code is below and codepen here: https://codepen.io/Alexander9111/pen/PowLQZO
HTML:
<svg width=1000 height="1000">
<g class="element" transform="translate(479, 247) scale(1)">
<rect stroke="blue" fill="blue" x="0" y="0" height="200" width="450"/>
<text>479</text>
</g>
<g class="element" transform="translate(874, 145) scale(1)">
<rect stroke="red" fill="red" x="0" y="0" height="250" width="300"/>
<text>874</text>
</g>
<g class="element" transform="translate(643, 356) scale(1)">
<rect stroke="green" fill="green" x="0" y="0" height="200" width="350"/>
<text>643</text>
</g>
</svg>
And Javascript:
const svg = document.querySelector("svg");
const groups = [...document.querySelectorAll("g")];
groups.map(child => {
console.log(getValue(child))
});
function getValue(child){
var transform = child.getAttribute("transform")
.replace("translate(","")
.replace(/\) scale.*/i,"");
return transform.split(",")
.map(el => parseInt(el));
}
groups.sort((a,b) => {
return getValue(b)[0] - getValue(a)[0];
})
groups.forEach((el,index) => {
svg.appendChild(el);
});
You could adapt the line return getValue(b)[0] - getValue(a)[0]; to a - b and then it sorts ascending instead of descending. Also you can change the index from (a)[0] to (a)[1] to sort by y-translation instead.
I'm really not familiar with SVG's so I'm sorry if this is actually a fairly easy problem..
I'm creating an SVG:
<svg height="100%" width="100%">
<rect x="0" y="0" width="100%" height="100%" fill="#da552f"></rect>
<image xlink:href="https://d30y9cdsu7xlg0.cloudfront.net/noun-svg/703414.svg?Expires=1481685113&Signature=hsa76aA6t5W6xisN8bYKk5t74cmOzTXmYUObaVwE0hUso99Gb4czprrsQAtkaC0aOQJBhNfAn8MjRpKyu8M~AzS5OS3rthGOLFqa3Pk2lCwAWjs-KtTa9fSo7w-sZSJwG6LDeRm5B6T5hYnoKQLibJzCtHvSdUYlp5XBUx1RNvs_&Key-Pair-Id=APKAI5ZVHAXN65CHVU2Q" transform="translate(-35.5,-31)" x="50%" y="50%" height="50px" width="50px"/>
<text fill="#ffffff" x="50%" y="50%" alignment-baseline="middle" text-anchor="middle" font-size="48" font-family="Verdana">Kitty Cat</text>
</svg>
And as you can see both the image of the cat and the text are centered in the rectangle, but this isn't the desired effect I want.
I'd like the image to be next to the text and both of them be centered in the rectangle.. example:
How is this doable using SVGs? Is javascript required? Any help would be great! Thanks
Unlike HTML, SVG has no automatic layout of groups of elements.
You have two choices:
Cheat and put your image and text in HTML and use a <foreignObject> element to embed the HTML in your SVG. Although it is barely an SVG any more. And that only works in browsers.
Use Javascript to measure the text and then re-position it in the centre.
function reCentre() {
var svg = document.getElementById("mysvg");
var group = document.getElementById("centreMe");
// Get the bounding box of the image+text group
var groupBounds = group.getBBox();
// Get the size of the SVG on the page
var svgBounds = svg.getBoundingClientRect();
// Calculate new position for the group
var groupPosX = (svgBounds.width - groupBounds.width) / 2;
var groupPosY = (svgBounds.height - groupBounds.height) / 2;
// Calculate the difference between the groups current position
// and where it needs to be in order to be centred.
var dx = groupPosX - groupBounds.x;
var dy = groupPosY - groupBounds.y;
// Give the group a translate transform to move it to this new position
group.setAttribute("transform", "translate("+dx+","+dy+")");
}
// Initial centering
reCentre();
// Also recentre when window resizes
window.addEventListener("resize", reCentre);
<svg id="mysvg" height="100%" width="100%">
<rect x="0" y="0" width="100%" height="100%" fill="#da552f"></rect>
<g id="centreMe">
<image xlink:href="https://d30y9cdsu7xlg0.cloudfront.net/noun-svg/703414.svg?Expires=1481685113&Signature=hsa76aA6t5W6xisN8bYKk5t74cmOzTXmYUObaVwE0hUso99Gb4czprrsQAtkaC0aOQJBhNfAn8MjRpKyu8M~AzS5OS3rthGOLFqa3Pk2lCwAWjs-KtTa9fSo7w-sZSJwG6LDeRm5B6T5hYnoKQLibJzCtHvSdUYlp5XBUx1RNvs_&Key-Pair-Id=APKAI5ZVHAXN65CHVU2Q" x="0" y="-50" height="50px" width="50px"/>
<text fill="#ffffff" x="80" y="0" font-size="48" font-family="Verdana">Kitty Cat</text>
</g>
</svg>
Edit the x and y attributes of the image tag until the cat face is where you would like it.
<svg height="100%" width="100%">
<rect x="0" y="0" width="100%" height="100%" fill="#da552f"></rect>
<image xlink:href="https://d30y9cdsu7xlg0.cloudfront.net/noun-svg/703414.svg?Expires=1481685113&Signature=hsa76aA6t5W6xisN8bYKk5t74cmOzTXmYUObaVwE0hUso99Gb4czprrsQAtkaC0aOQJBhNfAn8MjRpKyu8M~AzS5OS3rthGOLFqa3Pk2lCwAWjs-KtTa9fSo7w-sZSJwG6LDeRm5B6T5hYnoKQLibJzCtHvSdUYlp5XBUx1RNvs_&Key-Pair-Id=APKAI5ZVHAXN65CHVU2Q" transform="translate(-35.5,-31)" x="25%" y="45%" height="50px" width="50px"/>
<text fill="#ffffff" x="50%" y="50%" alignment-baseline="middle" text-anchor="middle" font-size="48" font-family="Verdana">Kitty Cat</text>
</svg>
you could use a webfont or an emoji instead of an image...
svg {
position: absolute;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px
}
<svg viewBox="0 0 400 200">
<rect x="0" y="0" width="400" height="200" fill="pink" />
<text x="200" y="100" dominant-baseline="middle" text-anchor="middle" font-size="30" font-family="sans serif">
<tspan font-size="50">🐱</tspan>Kitty Cat</text>
</svg>
I wish to fit svg text inside a rect. I could use an approach to compare the widths and add line breaks to the text, but it's not tedious.
Is there a more elegant way than this? Maybe by using CSS or d3?
UPDATE:the following code appends foreignObject using d3 but the div is not displayed. (it is there in the code inspecter)
var group = d3.select("#package");
var fo = group.append("foreignObject").attr("x", 15).attr("y", 15).attr("width", 190).attr("height", 90);
fo.append("div").attr("xmlns", "http://www.w3.org/1999/xhtml").attr("style", "width:190px; height:90px; overflow-y:auto").text("Thiggfis the dgdexsgsggs wish to fit insidegssgsgs");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<p id="p"></p>
<svg width="220" height="120" viewBox="0 0 220 120" id="package">
<rect x="10" y="10" width="200" height="100" fill="none" stroke="black"/>
</svg>
A namespace cannot be assigned by attr, it's a side effect of element creation. You need an html div so you need to tell d3 that by calling the element xhtml:div, once you do that, d3 will do the rest.
var group = d3.select("#package");
var fo = group.append("foreignObject").attr("x", 15).attr("y", 15).attr("width", 190).attr("height", 90);
fo.append("xhtml:div").attr("style", "width:190px; height:90px; overflow-y:auto").text("Thiggfis the dgdexsgsggs wish to fit insidegssgsgs");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<p id="p"></p>
<svg width="220" height="120" viewBox="0 0 220 120" id="package">
<rect x="10" y="10" width="200" height="100" fill="none" stroke="black"/>
</svg>
Here's a simple example of a foreignObject used to insert HTML markup into an SVG:
<svg width="220" height="120" viewBox="0 0 220 120">
<rect x="10" y="10" width="200" height="100" fill="none" stroke="black" />
<foreignObject x="15" y="15" width="190" height="90">
<div xmlns="http://www.w3.org/1999/xhtml" style="width:190px; height:90px; overflow-y:auto"><b>This</b> is the <i>text</i> I wish to fit inside <code>rect</code></div>
</foreignObject>
</svg>
I have the following SVG code. The SVG with id "nestedsvg" is being appended in the HTML, I can view it on the console. But it's not visible on the screen. I tried assigning it a z-index of 99 but still it's invisible. Where am I going wrong?
<svg data="BusinessRoleFigure" x="144" y="95"
width="128" height="66" id="outer" style="position: relative;">
<rect x="0" y="0" width="100%" height="100%"
stroke="rgb(178,178,126)" stroke-width="1" fill="rgb(255,255,181)"
style="position: relative;"></rect>
<svg id="nestedsvg" x="100%" height="100" width="50">
<rect x="-50" rx="5" ry="5" width="20" height="10" stroke="black"
stroke-width="1" fill="black" z-index="99"></rect>
</svg>
<circle cx="118" cy="13" r="5" fill="none"
stroke-linejoin="round" stroke="black"
z-index="1" stroke-width="1"></circle>
</svg>
Jsfiddle: http://jsfiddle.net/MxHPq/145/
This is because the rectangle you are drawing is outside of the nested SVG viewport.
That SVG has a width and height of 100x50, and you are drawing a 20x10 rectangle at (-50,0). Meaning the rectangle covers the area from (-50,0) to (-30,10). So it is not visible. By default, objects outside a nested SVG viewport are not visible.
There are two ways to fix this:
Make objects outside the viewport visible. You can do this by setting overflow="visible" on the nested SVG.
<svg data="BusinessRoleFigure" x="144" y="95" width="128" height="66" id="outer">
<rect x="0" y="0" width="100%" height="100%" stroke="rgb(178,178,126)" stroke-width="1" fill="rgb(255,255,181)"></rect>
<svg id="nestedsvg" x="100%" height="100" width="50" overflow="visible">
<rect x="-50" rx="5" ry="5" width="20" height="10" stroke="black" stroke-width="1" fill="black"></rect>
</svg>
<circle cx="118" cy="13" r="5" fill="none" stroke-linejoin="round" stroke="black" stroke-width="1"></circle>
</svg>
Move the rectangle inside the SVG viewport and reposition the SVG so that the rectangle ends up in the same place.
I don't know why you wanted the nested SVG to be at x="100%", but you would need to change that if you go with this solution.
<svg data="BusinessRoleFigure" width="128" height="66" id="outer">
<rect x="0" y="0" width="100%" height="100%" stroke="rgb(178,178,126)" stroke-width="1" fill="rgb(255,255,181)"></rect>
<svg id="nestedsvg" x="78" height="100" width="50">
<rect x="0" rx="5" ry="5" width="20" height="10" stroke="black" stroke-width="1" fill="black"></rect>
</svg>
<circle cx="118" cy="13" r="5" fill="none" stroke-linejoin="round" stroke="black" stroke-width="1"></circle>
</svg>
A few other notes about your original SVG:
x and y coordinates on the root <svg> element have no effect.
z-index currently has no meaning in SVGs. Although this may change for the upcoming SVG2 standard.
position: relative has no meaning in SVGs.
I've removed these things from my modified examples.