Drawing SVG into Canvas and manipulating drawn elements using their IDs - javascript

I have an SVG file loaded into an <object> tag. I am using javascript to manipulate some elements within this svg. For example:
var theSvgXml = document.getElementById('theObject').contentDocument;
theSvgXml.getElementById('theElementId').style.display = 'inline';
theSvgXml.getElementById('theElementId').style.fill = 'red';
theSvgXml.getElementById('anotherElement').style.display = 'none';
This works perfectly and all was well. But i am wondering if the same thing can be done with canvas. I have read about kinetic js, fabric js, canvg js as well, and i saw the various methods of loading the svg file into the canvas either by the file directory, the xml or through an image.
But after drawing this svg file into the canvas, can i manipulate the elements by their IDs?
The SVG is created using Adove Illustrator, and each layer or group is given an id with can be accessed using css selectors. Again, can this be done in canvas after drawing the SVG onto it. (Please note that the SVG is HUGE and the only reason i am thinking about the canvas solution is because of the svg not showing the illustrator multiply effect to create a shadow)
Any help will be highly appreciated. Thank you.
Code Snippet:
<g id="Pockets">
<g id="Pen__x26__Radio_Arm_Pocket" class="st791"> … </g>
<g id="Pen_Pocket_Arm" class="st791"> … </g>
<g id="Card_Zipper_Arm_Pocket" class="st791"> … </g>
<g id="Radio_Pocket_Arm_Pocket" class="st791"> … </g>
<g id="Angled_Chest_Pocket_Right" class="st791"> … </g>
<g id="Angled_Chest_Pocket_Left" class="st791"> … </g>
<g id="Angled_Chest_Pocket_left_and_Right" class="st791"> … </g>
<g id="Chest_Pocket_Right" class="st791"> … </g>
<g id="Chest_Pocket_Left" class="st791"> … </g>
<g id="Chest_Pocket_left_and_Right" class="st791"> … </g>
<g id="Tool_Pocket" class="st791"> … </g>
<g id="Cargo_x2F_Mobile_Pocket_Velcro" class="st791"> … </g>
<g id="Cargo_x2F_Mobile_Pocket_Zip" class="st791"> … </g>
<g id="Cargo_x2F_Mobile_Pocket_Button" class="st791"> … </g>
<g id="Cargo_Pocket_Velcro" class="st791"> … </g>
<g id="Cargo_Pocket_Button" class="st791"> … </g>
<g id="Cargo_Pocket_Zip" class="st791"> … </g>
<g id="Back_Pocket_Right_Velcro" class="st791"> … </g>
<g id="Back_Pocket_left_Velcro" class="st791"> … </g>
<g id="Back_Pocket_left_and_Right_Velcro" class="st791"> … </g>
<g id="Back_Pocket_Right_Velcro_Button" class="st791"> … </g>
<g id="Back_Pocket_left_Velcro_Button" class="st791"> … </g>
<g id="Back_Pocket_left_and_Right_Button" class="st791"> … </g>
<g id="Back_Pocket_Right_Zip" class="st791"> … </g>
<g id="Back_Pocket_left_Zip" class="st791"> … </g>
<g id="Back_Pocket_left_and_Right_Zip" class="st791"> … </g>
</g>
As you can see form the xml snippet after exporting the file from adobe illustrator, each group is set with an ID. How can preserve these in canvas as objects (as Fabrics.js suggests using getObjects() method)? Is there a way to achieve this? If yes, how can i reference these groups? Also, the shadow is a key issue and i do not want ot use flash. Thanks

Here's how to do this with Fabric:
fabric.loadSVGFromURL('/assets/72.svg', function(objects, options){
var group = fabric.util.groupSVGElements(objects, options);
group
.set({ left: 300, top: 200 })
.scaleToWidth(500)
.setCoords();
canvas.add(group);
}, reviver);
function reviver(element, object) {
object.id = element.getAttribute('id');
}
The code should be pretty self-explanatory. We load SVG; Fabric parses it internally, spitting out set of objects representing each element. We then group those elements and add them onto canvas in one chunk. Reviver is responsible for reading id off of each SVG element and assigning it to a corresponding fabric instance.
Run this snippet in http://fabricjs.com/kitchensink/ and you get:
Let's inspect this grouped object:
canvas.item(0) + ''; "#<fabric.PathGroup (29303): { top: 200, left: 300 }>"
And its children:
canvas.item(0).getObjects(); // Array[2287]
Let's retrieve one by id:
var greenland = canvas.item(0).getObjects().filter(function(obj) {
return obj.id === 'path4206';
})[0];
This is all plain old Javascript, as you can see. Let's change color of that particular object/shape now:
greenland.fill = 'red';

<canvas> operates on pixels, it doesn't have the concept of objects/elements like SVG. So to maniupulate the image you'd need to manipulate the underlying SVG and re-render it to canvas after every change.
You can put SVG image on <canvas> using .drawImage method.
var cvs = document.createElement('canvas'), ctx = cvs.getContext('2d');
cvs.width = 600;
cvs.height = 300;
document.body.appendChild(cvs);
var img = new Image();
img.width = '600';
img.height = '300';
img.onload = function(){
ctx.drawImage(img,0,0);
}
img.src = 'file.svg';
But you can't manipulate SVG created this way. To do this you should try to convert an <svg> element DOM do base46 encoded string, set it an a source of an image, then render to the canvas.
So in the example above instead of img.src = 'file.svg' you'd need
img.src = 'data:image/svg+xml;base64,' + btoa( document.getElementById('mySvgElement').outerHTML );

Just some random thoughts about your situation
While html canvas does have a few compositing modes, canvas doesn't have an image multiply blend.
However, Firefox does! It's a multiply blend extension to compositing:
ctx.globalCompositeOperation = 'multiply';
The major canvas libraries that have SVG-->Canvas translators are FabricJS and KineticJS, but neither of them have implemented this multiply filter yet. Of the two, FabricJS is more SVG capable at this point and I see Kangax (FabricJS's creator) has commented on your post. You might ask him really nicely if he would add a multiply filter ;)
Since you seem to have access to Adobe Illustrator, you might try out Mike Swanson's impressive SVG-->Canvas translator. I don't know if it handles image filters, but it does an impressive job of taking standard Adobe Illustrator SVGs and creating Canvas drawings (very impressive app, if you ask me!): http://blog.mikeswanson.com/post/29634279264/ai2canvas
Thinking inside SVG -- you should check out the SVGJS library:
SVGJS is an SVG library that lets you manipulate SVG elements by ID.
https://svgdotjs.github.io/
There is also an extension that imports from Illustrator:
https://svgdotjs.github.io/importing-exporting/
And finally SVGJS also has an extension that does a darken image filter (not multiply, but close)
https://svgdotjs.github.io/plugins/svg-filter-js/
If you get desperate...(unlikely you'll get this desperate!)
You could "roll your own" multiply filter by grabbing the canvas pixels with context.getImageData and then running this function on each of the r,g,b elements of the pixels you want to multiply.
function multiply(top, bottom){
return(top*bottom/255;
}
Good luck!

If you use a framework like kinetic then you can access and manipulate layers and objects by their id's or names.

Related

Dynamically generated SVG not using clip-path

I have an SVG file that I import with Vue JS, using vite-svg-loader. I import the file as a raw string, like so:
import DelawareBounds from './assets/images/DelawareOutlineNew.min.svg?raw'
Then, I read the string into an SVG element like so:
const parser = new DOMParser();
const DelawareMask = parser.parseFromString(DelawareBounds, "image/svg+xml").documentElement
I then add some content to the svg and add a clip-path from #DelawareBounds that already existed in the svg
const dataGroup = document.createElementNS('http://www.w3.org/2000/svg','g')
dataGroup.setAttributeNS('http://www.w3.org/2000/svg','id','data')
dataGroup.setAttributeNS('http://www.w3.org/2000/svg','clip-path','url(#DelawareBounds)')
let pathGroup
for (let path of paths) {
pathGroup = document.createElementNS('http://www.w3.org/2000/svg','g')
pathGroup.setAttribute('style','transform: scale('+xScale+','+yScale+')')
pathGroup.setAttributeNS('http://www.w3.org/2000/svg','class','delaware-bounds-scale')
pathGroup.appendChild(path)
dataGroup.appendChild(pathGroup)
}
DelawareMask.appendChild(dataGroup)
The clip-path does not work when I add the content this way. If I take the generated content and paste it into a new file, the clip-path works perfectly.
From my research, the most of these types of issues comes down to making sure to allocating the proper svg namespace. For all my dynamic content, I've made sure to add the namespace.
The only thing I can think of is that when I'm parsing the imported svg string, the data content is not going into the proper namespace. I'm not sure what else to do here? Any suggestions are appreciated.
Before the dynamic content is added, the svg looks like this:
<svg version="1.2" viewBox="0 0 2431 5145" xmlns="http://www.w3.org/2000/svg" fill="none">
<defs>
<clipPath id="DelawareBounds">
<path d="...some content here..."/>
</clipPath>
</defs>
</svg>
after the dynamic content is added, the svg looks like this:
<svg version="1.2" viewBox="0 0 2431 5145" xmlns="http://www.w3.org/2000/svg" fill="none">
<defs>
<clipPath id="DelawareBounds">
<path d="...some content here..."/>
</clipPath>
</defs>
<g id="data" clip-path="url(#DelawareBounds)">
...some data here...
</g>
</svg>
The result is that the data shows appropriately, but the clip-path does not clip the data content.
I found a solution to my problem, but still curious if there are other ways to do this.
My solution was to include:
<g id="data" clip-path="url(#DelawareBounds)"></g>
Then adding content inside the #data group worked. Instead of dynamically generating that line above as well as the content that goes inside.
Generally only elements are created in a specific namespace.
Attributes are usually in the null namespace, so the correct code is.
const dataGroup = document.createElementNS('http://www.w3.org/2000/svg','g')
dataGroup.setAttribute('id','data')
dataGroup.setAttribute('clip-path','url(#DelawareBounds)')
let pathGroup
for (let path of paths) {
pathGroup = document.createElementNS('http://www.w3.org/2000/svg','g')
pathGroup.setAttribute('style','transform: scale('+xScale+','+yScale+')')
pathGroup.setAttribute('class','delaware-bounds-scale')
pathGroup.appendChild(path)
dataGroup.appendChild(pathGroup)
}
DelawareMask.appendChild(dataGroup)

External SVG sprites and .childnodes

I have a site with several svg icons and svg logo that I have to animate.
For a better readability, I use a sprite system on an external file.
I use XMLHttpRequests to load sprites at the beginning of the request.
function getSprites(url){
var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.send();
ajax.onload = function() {
var div = document.createElement("div");
div.innerHTML = ajax.responseText;
document.body.insertBefore(div, document.body.childNodes[0]);
}
}
getSprites("./assets/images/sprites-icon.svg");
getSprites("./assets/images/sprites-logo.svg");
as soon as I use queryselector to select an element and animate it, this one is undefined
for example
let shapeLogoRoadmap = document.querySelector('.js-shape-roadmap-logo').childNodes;
and here an example of svg symbol from sprite
<symbol id="roadmap-small-logo" viewBox="0 0 250 250">
<g class="js-shape-roadmap-logo">
<path fill="#93718d" style="fill: var(--first-color, #93718d)" filter="url(#AI_Shadow_2)" d="M219.4366,111.5074l-80.944-80.944a19.1431,19.1431,0,0,0-26.9852,0l-80.944,80.944a19.1431,19.1431,0,0,0,0,26.9852l80.944,80.944a19.1431,19.1431,0,0,0,26.9852,0l80.944-80.944A19.1431,19.1431,0,0,0,219.4366,111.5074ZM200.5485,135.791,135.791,200.5485a15.3013,15.3013,0,0,1-21.582,0L49.4515,135.791a15.3013,15.3013,0,0,1,0-21.582L114.209,49.4515a15.3013,15.3013,0,0,1,21.582,0l64.7575,64.7575A15.3013,15.3013,0,0,1,200.5485,135.791Z"/>
<path fill="#977792" style="fill: var(--second-color, #977792)" filter="url(#AI_Shadow_2)" d="M201.15,114.1231,135.8769,48.85a15.4233,15.4233,0,0,0-21.7538,0L48.85,114.1231a15.4233,15.4233,0,0,0,0,21.7538L114.1231,201.15a15.4233,15.4233,0,0,0,21.7538,0L201.15,135.8769A15.4233,15.4233,0,0,0,201.15,114.1231Zm-15.2308,19.5807-52.2154,52.2154a12.3428,12.3428,0,0,1-17.4077,0L64.0808,133.7038a12.3428,12.3428,0,0,1,0-17.4077l52.2153-52.2153a12.3428,12.3428,0,0,1,17.4077,0l52.2154,52.2153A12.3428,12.3428,0,0,1,185.9192,133.7038Z"/>
<path fill="#9c7d96" style="fill: var(--third-color, #9c7d96)" filter="url(#AI_Shadow_2)" d="M185.9192,116.2961,133.7038,64.0808a12.3428,12.3428,0,0,0-17.4077,0L64.0808,116.2961a12.3428,12.3428,0,0,0,0,17.4077l52.2153,52.2154a12.3428,12.3428,0,0,0,17.4077,0l52.2154-52.2154A12.3428,12.3428,0,0,0,185.9192,116.2961Zm-12.1846,15.6654-41.7731,41.7731a9.87,9.87,0,0,1-13.923,0L76.2654,131.9615a9.87,9.87,0,0,1,0-13.923l41.7731-41.7731a9.87,9.87,0,0,1,13.923,0l41.7731,41.7731A9.87,9.87,0,0,1,173.7346,131.9615Z"/>
<path fill="#a0829b" style="fill: var(--fourth-color, #a0829b)" filter="url(#AI_Shadow_2)" d="M173.7346,118.0385,131.9615,76.2654a9.87,9.87,0,0,0-13.923,0L76.2654,118.0385a9.87,9.87,0,0,0,0,13.923l41.7731,41.7731a9.87,9.87,0,0,0,13.923,0l41.7731-41.7731A9.87,9.87,0,0,0,173.7346,118.0385Zm-9.7461,12.5307-33.4193,33.4193a7.8951,7.8951,0,0,1-11.1384,0L86.0115,130.5692a7.8951,7.8951,0,0,1,0-11.1384l33.4193-33.4193a7.8949,7.8949,0,0,1,11.1384,0l33.4193,33.4193A7.8951,7.8951,0,0,1,163.9885,130.5692Z"/>
<path fill="#a98ea4" style="fill: var(--fifth-color, #a98ea4)" filter="url(#AI_Shadow_2)" d="M163.9885,130.5692l-33.4193,33.4193a7.8951,7.8951,0,0,1-11.1384,0L86.0115,130.5692a7.8951,7.8951,0,0,1,0-11.1384l33.4193-33.4193a7.8949,7.8949,0,0,1,11.1384,0l33.4193,33.4193A7.8951,7.8951,0,0,1,163.9885,130.5692Z"/>
</g>
</symbol>
I tried setinterval on animation but without success
In this situation, I want to have access to each path because I animate them one after the other.
Should I give them the same class name? or?
svg are as clear as possible, but I prefer to avoid inline svg but if there is no other better solution....
I need to have access to each path of the svg, the animations are not just transferring an image from right to left but a little more complex
I use gsap to animate just for information
I read that you can have problems with childnodes in this kind of situation?
To summarize, I would like to be able to manage each path of my svg, keeping a good organization.
Thx !
Once the page is loaded, in the console, I have access to the paths
When I refresh the page mutltiple time, sometimes it works !! :/
I found a solution with the help of the GSAP forum.
Clean!
Thx Blake from GSAP
window.mySvg = window.mySvg || {};
window.mySvg.logo = `
<svg>
...
</svg>
`;
document.body.insertAdjacentHTML("afterbegin", mySvg.logo);

Paperjs SVG import: How to access group id's

In paperjs I'm importing an SVG file that has elements like this:
<g id="Layer_4">
<circle fill="#F42700" cx="114.5" cy="249.5" r="50"/>
<circle fill="#F42700" cx="385.5" cy="249.5" r="50"/>
</g>
<g id="Layer_3">
<path fill="#8A0055" d="M408,263l-36-0.3V38c0-0.3-..."/>
</g>
Those top level groups are accessible in the parsed SVG as direct children of the created SVG object. But aside from their order, is there any way I can retrieve the original id parameter?
Top level group ids turn into item.name parameters, like:
paper.project.import("path/to/svg.svg", function (item) {
console.log(item.firstChild.name)
}
As per this comment.

How to use z-index in svg elements?

I'm using the svg circles in my project like this,
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 120">
<g>
<g id="one">
<circle fill="green" cx="100" cy="105" r="20" />
</g>
<g id="two">
<circle fill="orange" cx="100" cy="95" r="20" />
</g>
</g>
</svg>
And I'm using the z-index in the g tag to show the elements the first. In my project I need to use only z-index value, but I can't use the z-index to my svg elements. I have googled a lot but I didn't find anything relatively.
So please help me to use z-index in my svg.
Here is the DEMO.
Specification
In the SVG specification version 1.1 the rendering order is based on the document order:
first element -> "painted" first
Reference to the SVG 1.1. Specification
3.3 Rendering Order
Elements in an SVG document fragment have an implicit drawing order, with the first elements in the SVG document fragment getting "painted" first. Subsequent elements are painted on top of previously painted elements.
Solution (cleaner-faster)
You should put the green circle as the latest object to be drawn. So swap the two elements.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="30 70 160 120">
<!-- First draw the orange circle -->
<circle fill="orange" cx="100" cy="95" r="20"/>
<!-- Then draw the green circle over the current canvas -->
<circle fill="green" cx="100" cy="105" r="20"/>
</svg>
Here the fork of your jsFiddle.
Solution (alternative)
The tag use with the attribute xlink:href (just href for SVG 2) and as value the id of the element. Keep in mind that might not be the best solution even if the result seems fine. Having a bit of time, here the link of the specification SVG 1.1 "use" Element.
Purpose:
To avoid requiring authors to modify the referenced document to add an ID to the root element.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="30 70 160 120">
<!-- First draw the green circle -->
<circle id="one" fill="green" cx="100" cy="105" r="20" />
<!-- Then draw the orange circle over the current canvas -->
<circle id="two" fill="orange" cx="100" cy="95" r="20" />
<!-- Finally draw again the green circle over the current canvas -->
<use xlink:href="#one"/>
</svg>
Notes on SVG 2
SVG 2 Specification is the next major release and still supports the above features.
3.4. Rendering order
Elements in SVG are positioned in three dimensions. In addition to their position on the x and y axis of the SVG viewport, SVG elements are also positioned on the z axis. The position on the z-axis defines the order that they are painted.
Along the z axis, elements are grouped into stacking contexts.
3.4.1. Establishing a stacking context in SVG
...
Stacking contexts are conceptual tools used to describe the order in which elements must be painted one on top of the other when the document is rendered, ...
SVG 2 Support Mozilla - Painting
How do I know if my browser supports svg 2.0
Can I use SVG
Deprecated XLink namespace For SVG 2 use href instead of the additional deprecated namespace xlink:href (Thanks G07cha)
As others here have said, z-index is defined by the order the element appears in the DOM. If manually reordering your html isn't an option or would be difficult, you can use D3 to reorder SVG groups/objects.
Use D3 to Update DOM Order and Mimic Z-Index Functionality
Updating SVG Element Z-Index With D3
At the most basic level (and if you aren't using IDs for anything else), you can use element IDs as a stand-in for z-index and reorder with those. Beyond that you can pretty much let your imagination run wild.
Examples in code snippet
var circles = d3.selectAll('circle')
var label = d3.select('svg').append('text')
.attr('transform', 'translate(' + [5,100] + ')')
var zOrders = {
IDs: circles[0].map(function(cv){ return cv.id; }),
xPos: circles[0].map(function(cv){ return cv.cx.baseVal.value; }),
yPos: circles[0].map(function(cv){ return cv.cy.baseVal.value; }),
radii: circles[0].map(function(cv){ return cv.r.baseVal.value; }),
customOrder: [3, 4, 1, 2, 5]
}
var setOrderBy = 'IDs';
var setOrder = d3.descending;
label.text(setOrderBy);
circles.data(zOrders[setOrderBy])
circles.sort(setOrder);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 100">
<circle id="1" fill="green" cx="50" cy="40" r="20"/>
<circle id="2" fill="orange" cx="60" cy="50" r="18"/>
<circle id="3" fill="red" cx="40" cy="55" r="10"/>
<circle id="4" fill="blue" cx="70" cy="20" r="30"/>
<circle id="5" fill="pink" cx="35" cy="20" r="15"/>
</svg>
The basic idea is:
Use D3 to select the SVG DOM elements.
var circles = d3.selectAll('circle')
Create some array of z-indices with a 1:1 relationship with your SVG elements (that you want to reorder). Z-index arrays used in the examples below are IDs, x & y position, radii, etc....
var zOrders = {
IDs: circles[0].map(function(cv){ return cv.id; }),
xPos: circles[0].map(function(cv){ return cv.cx.baseVal.value; }),
yPos: circles[0].map(function(cv){ return cv.cy.baseVal.value; }),
radii: circles[0].map(function(cv){ return cv.r.baseVal.value; }),
customOrder: [3, 4, 1, 2, 5]
}
Then, use D3 to bind your z-indices to that selection.
circles.data(zOrders[setOrderBy]);
Lastly, call D3.sort to reorder the elements in the DOM based on the data.
circles.sort(setOrder);
Examples
You can stack by ID
With leftmost SVG on top
Smallest radii on top
Or Specify an array to apply z-index for a specific ordering -- in my example code the array [3,4,1,2,5] moves/reorders the 3rd circle (in the original HTML order) to be 1st in the DOM, 4th to be 2nd, 1st to be 3rd, and so on...
Try to invert #one and #two. Have a look to this fiddle : http://jsfiddle.net/hu2pk/3/
Update
In SVG, z-index is defined by the order the element appears in the document. You can have a look to this page too if you want : https://stackoverflow.com/a/482147/1932751
You can use use.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 120">
<g>
<g id="one">
<circle fill="green" cx="100" cy="105" r="20" />
</g>
<g id="two">
<circle fill="orange" cx="100" cy="95" r="20" />
</g>
</g>
<use xlink:href="#one" />
</svg>
The green circle appears on top.
jsFiddle
As discussed, svgs render in order and don't take z-index into account (for now). Maybe just send the specific element to the bottom of its parent so that it'll render last.
function bringToTop(targetElement){
// put the element at the bottom of its parent
let parent = targetElement.parentNode;
parent.appendChild(targetElement);
}
// then just pass through the element you wish to bring to the top
bringToTop(document.getElementById("one"));
Worked for me.
Update
If you have a nested SVG, containing groups, you'll need to bring the item out of its parentNode.
function bringToTopofSVG(targetElement){
let parent = targetElement.ownerSVGElement;
parent.appendChild(targetElement);
}
A nice feature of SVG's is that each element contains it's location regardless of what group it's nested in :+1:
Using D3:
If you want to re-inserts each selected element, in order, as the last child of its parent.
selection.raise()
Using D3:
If you want to add the element in the reverse order to the data, use:
.insert('g', ":first-child")
Instead of .append('g')
Adding an element to top of a group element
There is no z-index for svgs. But svg determines which of your elements are the uppermost by theire position in the DOM. Thus you can remove the Object and place it to the end of the svg making it the "last rendered" element. That one is then rendered "topmost" visually.
Using jQuery:
function moveUp(thisObject){
thisObject.appendTo(thisObject.parents('svg>g'));
}
usage:
moveUp($('#myTopElement'));
Using D3.js:
d3.selection.prototype.moveUp = function() {
return this.each(function() {
this.parentNode.appendChild(this);
});
};
usage:
myTopElement.moveUp();
This is the top Google result for searches regarding z-index and SVGs. After reading all the answers, some of which are very good, I was still confused.
So for rookies like me, here is the current summary, 9 years later in 2022.
You can't use z-index with SVGs.
In SVGs, z-index is defined by the order the element appears in the document.
If you want something to appear on top, or closer to the user, draw it last or insert it before. Source
SVG 2 could support z-index but might never come out
SVG 2 is a proposal to implement that and other features but it is at risk of never moving forward.
SVG 2 reached the Candidate Recommendation stage in 2016, and was revised in 2018 and the latest draft was released on 8 June 2021. Source
However it doesn't have a lot of support and very few people are working on it. Source So don't hold your breath waiting for this.
You could use D3 but probably shouldn't
D3 a commonly used to visualize data supports z-index by binding your z-index and then sorting but it is a large and complex library and might not be the best bet if you just want a certain SVG to appear on top of a stack.
The clean, fast, and easy solutions posted as of the date of this answer are unsatisfactory. They are constructed over the flawed statement that SVG documents lack z order. Libraries are not necessary either. One line of code can perform most operations to manipulate the z order of objects or groups of objects that might be required in the development of an app that moves 2D objects around in an x-y-z space.
Z Order Definitely Exists in SVG Document Fragments
What is called an SVG document fragment is a tree of elements derived from the base node type SVGElement. The root node of an SVG document fragment is an SVGSVGElement, which corresponds to an HTML5 <svg> tag. The SVGGElement corresponds to the <g> tag and permits aggregating children.
Having a z-index attribute on the SVGElement as in CSS would defeat the SVG rendering model. Sections 3.3 and 3.4 of W3C SVG Recommendation v1.1 2nd Edition state that SVG document fragments (trees of offspring from an SVGSVGElement) are rendered using what is called a depth first search of the tree. That scheme is a z order in every sense of the term.
Z order is actually a computer vision shortcut to avoid the need for true 3D rendering with the complexities and computing demands of ray tracing. The linear equation for the implicit z-index of elements in an SVG document fragment.
z-index = z-index_of_svg_tag + depth_first_tree_index / tree_node_qty
This is important because if you want to move a circle that was below a square to above it, you simply insert the square before the circle. This can be done easily in JavaScript.
Supporting Methods
SVGElement instances have two methods that support simple and easy z order manipulation.
parent.removeChild(child)
parent.insertBefore(child, childRef)
The Correct Answer That Doesn't Create a Mess
Because the SVGGElement (<g> tag) can be removed and inserted just as easily as a SVGCircleElement or any other shape, image layers typical of Adobe products and other graphics tools can be implemented with ease using the SVGGElement. This JavaScript is essentially a Move Below command.
parent.insertBefore(parent.removeChild(gRobot), gDoorway)
If the layer of a robot drawn as children of SVGGElement gRobot was before the doorway drawn as children of SVGGElement gDoorway, the robot is now behind the doorway because the z order of the doorway is now one plus the z order of the robot.
A Move Above command is almost as easy.
parent.insertBefore(parent.removeChild(gRobot), gDoorway.nextSibling())
Just think a=a and b=b to remember this.
insert after = move above
insert before = move below
Leaving the DOM in a State Consistent With the View
The reason this answer is correct is because it is minimal and complete and, like the internals of Adobe products or other well designed graphics editors, leaves the internal representation in a state that is consistent with the view created by rendering.
Alternative But Limited Approach
Another approach commonly used is to use CSS z-index in conjunction with multiple SVG document fragments (SVG tags) with mostly transparent backgrounds in all but the bottom one. Again, this defeats the elegance of the SVG rendering model, making it difficult to move objects up or down in the z order.
NOTES:
(https://www.w3.org/TR/SVG/render.html v 1.1, 2nd Edition, 16 August 2011)
3.3 Rendering Order Elements in an SVG document fragment have an implicit drawing order, with the first elements in the SVG document
fragment getting "painted" first. Subsequent elements are painted on
top of previously painted elements.
3.4 How groups are rendered Grouping elements such as the ‘g’ element (see container elements) have the effect of producing a temporary
separate canvas initialized to transparent black onto which child
elements are painted. Upon the completion of the group, any filter
effects specified for the group are applied to create a modified
temporary canvas. The modified temporary canvas is composited into the
background, taking into account any group-level masking and opacity
settings on the group.
Another solution would be to use divs, which do use zIndex to contain the SVG elements.As here:
https://stackoverflow.com/a/28904640/4552494
We have already 2019 and z-index is still not supported in SVG.
You can see on the site SVG2 support in Mozilla that the state for z-index – Not implemented.
You can also see on the site Bug 360148 "Support the 'z-index' property on SVG elements" (Reported: 12 years ago).
But you have 3 possibilities in SVG to set it:
With element.appendChild(aChild);
With parentNode.insertBefore(newNode, referenceNode);
With targetElement.insertAdjacentElement(positionStr, newElement); (No support in IE for SVG)
Interactive demo example
With all this 3 functions.
var state = 0,
index = 100;
document.onclick = function(e)
{
if(e.target.getAttribute('class') == 'clickable')
{
var parent = e.target.parentNode;
if(state == 0)
parent.appendChild(e.target);
else if(state == 1)
parent.insertBefore(e.target, null); //null - adds it on the end
else if(state == 2)
parent.insertAdjacentElement('beforeend', e.target);
else
e.target.style.zIndex = index++;
}
};
if(!document.querySelector('svg').insertAdjacentElement)
{
var label = document.querySelectorAll('label')[2];
label.setAttribute('disabled','disabled');
label.style.color = '#aaa';
label.style.background = '#eee';
label.style.cursor = 'not-allowed';
label.title = 'This function is not supported in SVG for your browser.';
}
label{background:#cef;padding:5px;cursor:pointer}
.clickable{cursor:pointer}
With:
<label><input type="radio" name="check" onclick="state=0" checked/>appendChild()</label>
<label><input type="radio" name="check" onclick="state=1"/>insertBefore()</label><br><br>
<label><input type="radio" name="check" onclick="state=2"/>insertAdjacentElement()</label>
<label><input type="radio" name="check" onclick="state=3"/>Try it with z-index</label>
<br>
<svg width="150" height="150" viewBox="0 0 150 150">
<g stroke="none">
<rect id="i1" class="clickable" x="10" y="10" width="50" height="50" fill="#80f"/>
<rect id="i2" class="clickable" x="40" y="40" width="50" height="50" fill="#8f0"/>
<rect id="i3" class="clickable" x="70" y="70" width="50" height="50" fill="#08f"/>
</g>
</svg>
Push SVG element to last, so that its z-index will be in top. In SVG, there s no property called z-index. try below javascript to bring the element to top.
var Target = document.getElementById(event.currentTarget.id);
var svg = document.getElementById("SVGEditor");
svg.insertBefore(Target, svg.lastChild.nextSibling);
Target: Is an element for which we need to bring it to top
svg: Is the container of elements
Move to front by transform:TranslateZ
Warning: Only works in FireFox
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 160" style="width:160px; height:160px;">
<g style="transform-style: preserve-3d;">
<g id="one" style="transform-style: preserve-3d;">
<circle fill="green" cx="100" cy="105" r="20" style="transform:TranslateZ(1px);"></circle>
</g>
<g id="two" style="transform-style: preserve-3d;">
<circle fill="orange" cx="100" cy="95" r="20"></circle>
</g>
</g>
</svg>
A better example of use, that I've ended up using.
<svg>
<defs>
<circle id="one" fill="green" cx="40" cy="40" r="20" />
<circle id="two" fill="orange" cx="50" cy="40" r="20"/>
</defs>
<use href="#two" />
<use href="#one" />
</svg>
To control the order you can change href attribute values of these use elements. This can be useful for animation.
Thanks to defs, circle elements are drawn only once.
jsfiddle.net/7msv2w5d
its easy to do it:
clone your items
sort cloned items
replace items by cloned
function rebuildElementsOrder( selector, orderAttr, sortFnCallback ) {
let $items = $(selector);
let $cloned = $items.clone();
$cloned.sort(sortFnCallback != null ? sortFnCallback : function(a,b) {
let i0 = a.getAttribute(orderAttr)?parseInt(a.getAttribute(orderAttr)):0,
i1 = b.getAttribute(orderAttr)?parseInt(b.getAttribute(orderAttr)):0;
return i0 > i1?1:-1;
});
$items.each(function(i, e){
e.replaceWith($cloned[i]);
})
}
$('use[order]').click(function() {
rebuildElementsOrder('use[order]', 'order');
/* you can use z-index property for inline css declaration
** getComputedStyle always return "auto" in both Internal and External CSS decl [tested in chrome]
rebuildElementsOrder( 'use[order]', null, function(a, b) {
let i0 = a.style.zIndex?parseInt(a.style.zIndex):0,
i1 = b.style.zIndex?parseInt(b.style.zIndex):0;
return i0 > i1?1:-1;
});
*/
});
use[order] {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="keybContainer" viewBox="0 0 150 150" xml:space="preserve">
<defs>
<symbol id="sym-cr" preserveAspectRatio="xMidYMid meet" viewBox="0 0 60 60">
<circle cx="30" cy="30" r="30" />
<text x="30" y="30" text-anchor="middle" font-size="0.45em" fill="white">
<tspan dy="0.2em">Click to reorder</tspan>
</text>
</symbol>
</defs>
<use order="1" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="0" y="0" width="60" height="60" style="fill: #ff9700; z-index: 1;"></use>
<use order="4" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="50" y="20" width="50" height="50" style="fill: #0D47A1; z-index: 4;"></use>
<use order="5" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="15" y="30" width="50" height="40" style="fill: #9E9E9E; z-index: 5;"></use>
<use order="3" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="25" y="30" width="80" height="80" style="fill: #D1E163; z-index: 3;"></use>
<use order="2" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="30" y="0" width="50" height="70" style="fill: #00BCD4; z-index: 2;"></use>
<use order="0" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="5" y="5" width="100" height="100" style="fill: #E91E63; z-index: 0;"></use>
</svg>
Just wanted to add a trick that works when you want to put a specific element on top.
function moveInFront(element) {
const svg = element.closest('svg'); // Find the parent SVG
svg.appendChild(element); // Append child moves the element to the end
}
This works because, and I quote the docs, "appendChild() moves [the element] from its current position to the new position" instead of adding a copy.
Note: If the element is nested, you would have to move the element to front within the group, and perhaps move the group to front as well.
use works for this purpose, but those elements that are placed with use help after is hard to manipulate...
What I couldn't figure out after I used it was: why I couldn't hover (neither mouseover, mouseenter manipulations from js would work) on the use elements to get additional functionality - like ~ showing text over the circles ~
After returned to circle reordering as it was only way to manipulate with those svg objects

How to clip content using a rect element in raphaeljs?

How a rect element can be used for clipping the content using rapaheljs ? I achieved this by creating the elements manually. The markup I created is given below and now I want to do this with raphaeljs.
<clipPath id="clipper">
<rect x="0" y="0" height="160" width="250"/>
</clipPath>
<g clip-path="url(#clipper)">
...
...
</g>
Or is there any other method using rapaheljs for creating a clipping rectangle like this ?
Any help would be appreciated. Thanks.
In Raphaël this is how:
elm.attr({clip-rect: "0 0 160 160"})
...where elm is the <g> element in your example.

Categories