Matter.js - 将html添加到body的选项

时间:2017-07-09 11:53:51

标签: javascript jquery html matterjs

我正在尝试matter js来创建落到重力的物体(物体)。下面是我用来创建的示例代码。我想在这个主体的顶部添加一个超链接,以便用户可以单击创建的主体并导航。有没有办法在Matter JS中创建的主体中添加或附加HTML代码。

    var phone = Matter.Bodies.rectangle(600, 200, 65, 45,  {
        id : 'phoneBody',
    density: 30.04,
    friction: 10.01,
    frictionAir: 0.00001,
    restitution: 0.2,

    render: {
        fillStyle: '#F35e66',
        strokeStyle: 'black',
        lineWidth: 1,
        sprite: {
                    texture: './images/phone.png'
                }
    }
});
Matter.World.add(world, phone); 

1 个答案:

答案 0 :(得分:0)

Matter.js中向主体声明超链接是自定义的实现(即event handling提供了诸如超链接的交互功能)。

此自定义实现将涉及以下内容:

  1. 定义给定主体的网址
  2. 声明鼠标事件处理程序具有交互性(即对mouseup事件做出反应)

实施细节

可以为给定的主体定义URL,如下所示:。

var phone = Matter.Bodies.rectangle(30, 50, 35, 55, {
              id : 'phoneBody',
              density: 30.04,
              friction: 0.15,
              frictionAir: 0.15,
              restitution: 0.2,
              render: { 
                fillStyle: '#F35e66',
                strokeStyle: 'black',
                lineWidth: 1
              },
              url: "https://www.phone.com"
            });

现在,您需要声明鼠标事件处理程序才能与世界上存在的物体进行交互。

这分两个阶段完成:   (i)声明与鼠标互动的对象并将其添加到世界中   (ii)声明鼠标事件处理程序以提供超链接功能

// Create a Mouse-Interactive object & add it to the World
render.mouse = Matter.Mouse.create(render.canvas);
var mouseInteractivity = Matter.MouseConstraint.create(engine, {
                          mouse: render.mouse,
                          constraint: {
                            stiffness: 0.2,
                            render: { visible: false }
                          }
                         });
Matter.World.add(engine.world, mouseInteractivity);

// Create a On-Mouseup Event-Handler
Events.on(mouseInteractivity, 'mouseup', function(event) {
  var mouseConstraint = event.source;
  var bodies = engine.world.bodies;
  if (!mouseConstraint.bodyB) {
    for (i = 0; i < bodies.length; i++) { 
      var body = bodies[i];
      if (Matter.Bounds.contains(body.bounds, mouseConstraint.mouse.position)) {
        var bodyUrl = body.url;
        console.log("Body.Url >> " + bodyUrl);
        // Hyperlinking feature
        if (bodyUrl != undefined) {
          window.open(bodyUrl, '_blank');
          console.log("Hyperlink was opened");
        }
        break;
      }
    }
  }
});

可以在CodePen >> https://codepen.io/anon/pen/xQEaQX?editors=0011

上随意进行上述实现
  

注意!为了使超链接正常工作,请不要忘记在您喜欢的Web浏览器上禁用弹出窗口阻止程序。