matter-js
matter-js copied to clipboard
Body out of 2 svg parts not displayed correctly?
I tried to create a body out of two svg parts. svgOne is the green one and svgTwo is the small red "H". But as soon as they are displayed as one body, the svgs are not looking correctly. Whats wrong here?
Appreciate any help, thanks in advance!
This is my code:
const vertexSets = [],
$('#svgOne').find('path').each(function(i, path){
var svgOne = Bodies.fromVertices(percentX(80), percentY(30), Matter.Vertices.scale(Svg.pathToVertices(path, 10), (window.innerWidth / 2000), (window.innerWidth / 2000)), {
render: {
fillStyle: '#009245',
strokeStyle: '#009245',
lineWidth: 1
}
}, true);
vertexSets.push(svgOne);
});
$('#svgTwo').find('path').each(function(i, path){
var svgTwo = Bodies.fromVertices(percentX(80), percentY(30), Matter.Vertices.scale(Svg.pathToVertices(path, 10), (window.innerWidth / 2000), (window.innerWidth / 2000)), {
render: {
fillStyle: '#F9420B',
strokeStyle: '#F9420B',
lineWidth: 1
}
}, true);
vertexSets.push(svgTwo);
});
const compoundSVG = Matter.Body.create({
parts: vertexSets
})
World.add(engine.world, [compoundSVG])
Matter.Runner.run(engine);
Render.run(render);
SVGs:
Result:
Looks like you need to set up poly-decomp
library as these will need to be decomposed, see docs for Bodies.fromVertices for info on that (check the examples too).
Thanks @liabru, but I have the decomp.js library referenced in my html file. Is there anything else to do? The svg files are displayed correctly when I render them separated (image 1)..
Thank you in advance!
I think what you should do is use a single Bodies.fromVertices(x, y, vertexSets...)
at the end and instead pass each part as an element of vertexSets
, since Body.create
doesn't do any decomposition (it expects convex vertices already).
Thanks @liabru, sounds logical! You mean like this?:
var svgOptions = {
parts: vertexSets
}
Matter.Bodies.fromVertices(percentX(80), percentY(30), svgOne, svgTwo, [svgOptions])
I tried this but getting an error. Could you maybe give me some more details, sorry I'm beginner to matter.js..
Thank you in advance!
Hey @liabru, still need a bit of help as I tried the last days but did not figure it out.. would you mind to give me some more details, please? Thanks so much in advance! :)
I think it might be that since vertexSets
is an array it would be more like [svgOne, svgTwo]
?
Thanks, but still not working.. :/
Hey @liabru, an alternative for me would be a sprite on a svg. But this ist not possible, right?