Skip to content

zOadT/svg2planck

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

svg2planck

DISCLAIMER: The current API is not stable and my change in the future.

About

This library utilizes node-xml2js to enable converting SVG files to Planck.js objects. It therefore provides functions to convert SVG shapes and transforms to corresponding Planck.js objects.

Usage

The exported function svg2planck wraps the function parseStringPromise from xml2js. Its API is similar to the original function but fixes some options and applies value processors to replace transform values by Planck's transform objects.

Currently there is no exported function to convert a SVG to a Planck.js world directy. But one can use the following code to do so:

import { svg2planck, Options, util, converters } from 'svg2planck'
import { World, Transform } from 'planck-js'

export async function simpleConverter(svg: string, options: Options) {
  const rootNode = await svg2planck(svg, options)
  return transformTree(rootNode, World(), Transform.identity())
}

function transformTree(node: any, world: World, transform: Transform) {
  if(util.isShape(node)) {
    let body = world.createBody({
      position: transform.p,
      angle: transform.q.getAngle()
    })
    for(let shape of converters.convertShape(node)) {
      body.createFixture(<any>shape)
    }
  } else if(node.$$) {
    if(node.$?.transform) {
      transform = Transform.mul(transform, <Transform>node.$.transform)
    }
    for(let child of node.$$) {
      transformTree(child, world, transform)
    }
  }
  return world
}

The function can then be used this way:

simpleConverter(svg, {
  meterPerPixelRatio: 0.1
}).then(world => {
  // ...
})

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published