Sprite图片没有出现在matter.js

时间:2017-07-12 20:31:56

标签: javascript html5 matterjs

我正在尝试用图片精灵替换标准circle body,但它没有显示图像。

var Engine = Matter.Engine,
  Render = Matter.Render,
  World = Matter.World,
  Bodies = Matter.Bodies,
  Body = Matter.Body,
  Constraint = Matter.Constraint,
  Vector = Matter.Vector,
  Events = Matter.Events,
  Mouse = Matter.Mouse,
  MouseConstraint = Matter.MouseConstraint;

// create an engine
var engine = Engine.create();

engine.world.gravity.y = 0; // gravity not needed in this app

// create a renderer
var render = Render.create({
  element: document.body,
  engine: engine
});

var ball_0 = Bodies.circle(100, 100, 11, {
  density: 0.04,
  frictionAir: 0.06,
  restitution: 0.8,
  friction: 0.01,
  render: {
    sprite: {
      texture: 'images/white.png',
      xScale: 20,
      yScale: 20
    }
  }
});

// add all of the bodies to the world
World.add(engine.world, ball_0);

// run the engine
Engine.run(engine);

// run the renderer
Render.run(render);
<script src="https://github.com/liabru/matter-js/releases/download/0.10.0/matter.min.js"></script>

2 个答案:

答案 0 :(得分:3)

您正在使用线框绘制所有内容。更改Render.create()来电以使用options: {wireframes: false}

关闭线框
// create a renderer
var render = Render.create({
  element: document.body,
  engine: engine,
  options: {wireframes: false}
});

答案 1 :(得分:0)

设置wireframes: false只能解决一半,您还需要先加载图像,然后再将其设置为纹理

必须先加载图像,然后再将其设置为“纹理”,否则会出现错误

  

HTMLImageElement处于“损坏”状态

对我来说,此问题最终导致打印900多个错误消息,使我的沙箱崩溃。

解决方案:我创建了一个简单的图像加载器:

const loadImage = (url, onSuccess, onError) => {
  const img = new Image();
  img.onload = () => {
    onSuccess(img.src);
  };
  img.onerror = onError();
  img.src = url;
};

然后我使用那个加载器加载纹理。加载纹理后,可以将其设置为Body对象的纹理。

 loadImage(
      "./assets/blue.jpg",
      url => {
        console.log("Success");
        World.add(world, [
          Bodies.circle(340, 340, 100, {
            density: 0.0005,
            frictionAir: 0.06,
            restitution: 0.3,
            friction: 0.01,
            render: {
              sprite: {
                texture: url // set texture here
              }
            }
          })
        ]);
      },
      () => {
        console.log("Error  Loading ");
      }
    );

重要:在致电Renderer.run()之前,必须禁用线框

// create renderer
var render = Render.create({
  element: document.body,
  engine: engine,
  options: {
    width: 800,
    height: 600,
    wireframes: false, // disable Wireframe
  }
});

Render.run(render);