将生成的路径缩放为与马提斯JS中加载的SVG路径相同的大小

时间:2019-02-20 11:44:03

标签: d3.js matter.js

我正在使用d3将保存的svg(在illustrator中创建)加载到预先命名的div中。 div还包含使用以下内容的canvas元素;

d3.xml("moniac.svg").mimeType("image/svg+xml").get(function (error, xml) {
    if (error) throw error;
    document.getElementById('moniac').appendChild(xml.documentElement);

然后,我设置了what.js物理引擎并添加了一个事件侦听器,以便当svg调整大小时,画布也按比例调整。到目前为止一切顺利。

const myCanvas = document.getElementById('water');
    const {
        clientWidth: width,
        clientHeight: height,
      } = document.querySelector('#moniac svg');
    const engine = Matter.Engine.create();
    const world = engine.world;
    const Bodies = Matter.Bodies;
    const Composites = Matter.Composites;
    const Common = Matter.Common;
    const Svg = Matter.Svg;
    const Vertices = Matter.Vertices;
    const render = Matter.Render.create({
    canvas: myCanvas,
    engine,
    options: {
      width,
      height,
      background: 'transparent',
      wireframes: false,
      showAngleIndicator: false,
    },
    });

然后我使用一个名为“ shape”的g元素从加载的svg中选择一组特定的路径和多边形,并通过以下函数将它们传递给函数以创建something.js静态顶点

    let paths = d3.select('#shape').selectAll('polygon')._groups[0];
    console.log ('polygons', paths )
    const vertex = [];
    paths.forEach((path) => {
      const vertices = d3.select(path).attr('points');
      let newShape = Matter.Vertices.fromPath(vertices);
      vertex.push(Vertices.scale(newShape, 1, 1))
    })


    paths = d3.select('#shape').selectAll('path')._groups[0];
    paths.forEach((path) => {
      const NUM_POINTS = 200
      let points = [];
      let len = path.getTotalLength();
      for (var i=0; i<=NUM_POINTS-1; i++) {
        let pt = path.getPointAtLength(i * len / (NUM_POINTS -1));
        points.push(pt.x, pt.y);
      }
      let newShape = Matter.Vertices.fromPath(String(points));
      vertex.push(newShape)
    })
    let newVertices = Matter.Bodies.fromVertices(width/2, height/2, vertex,{isStatic: true});
    Matter.World.add(world, newVertices);

...这似乎是问题所在,因为我创建的新顶点未缩放到与其创建的svg路径相同的位置,而我对如何使用它有些困惑我会这样做,因为我对something.js有点陌生。我是从调整大小功能应用刻度还是完全错误的?这是我目前拥有的,黑线是创建的顶点,白线是已加载的svg:

Depiction of the scaling/translation issue described

0 个答案:

没有答案