SVG.js, remove/read attribute “transform” from elements imported with “use”

霸气de小男生 提交于 2019-12-24 08:06:39

问题


I am using SVG.js to render a chessboard. The idea is, to keep the pieces in an external svg-file sprite.svg and include them with use, like this:

var pieceDrawn = svg.use(piece, "sprite.svg").move(x, y);

piece may be wp white pawn, in the sprite.svg:

<!-- white pawn //-->    
<g id="wp" transform="translate(225,0)">
    <path d="M 22,9 C 19.79,9 18,[...]"/>
</g>

sprite.svg was created in Sketch, therefore the group has an attribute transform. So when I move(x,y) the element, the transformation (255, 0) is added to the moving. How can I read the value of the transformation-attribute or remove it? pieceDrawn has no children(), select() seems not to be possible.


回答1:


After doing some research I found out that

it is not possible to access attributes from elements included from external files with use

because they are stored in a closed Shadow DOM.

Therefore, yesterday, I wrote a simple utility which can load SVG sprites into the page via XMLHttpRequest, removes transforms and unnecessary ids and allows to use elements from that sprite in SVGs of the webpage. Like this:

let svg = Svg.createSvg(document.getElementById("container"));
Svg.loadSprite("./assets/sprite.svg", ["star", "circle", "triangle", "smiley"]);
Svg.addElement(svg, "use", {"href": "#triangle", x: 10, y: 10});
Svg.addElement(svg, "use", {"href": "#smiley", x: 100, y: 10});

You can find it here: https://github.com/shaack/svjs-svg



来源:https://stackoverflow.com/questions/47435561/svg-js-remove-read-attribute-transform-from-elements-imported-with-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!