【问题标题】:Matter.js: placing text or images on the canvasMatter.js:在画布上放置文本或图像
【发布时间】:2022-04-05 09:35:03
【问题描述】:

我想在画布上放置字体或静态图像,但不确定使用 Matter.js 的最佳方法是什么。现在,对于图像,我只是创建一个大小为“0”的主体,并将图像 url 放在 render.sprite.texture 属性中。似乎可以解决问题,但是否有不同/更好的方式将静态图像放在画布上?

此外,在创建/绘制任何其他内容之前,我使用脚本顶部附近的“afterRender”事件将文本放到画布上:

_sceneEvents.push(
    Events.on(_engine, 'afterRender', function(event) {
        var context = _engine.render.context;
        context.font = "45px 'Cabin Sketch'";
        context.fillText("THROW OBJECT HERE", 150, 80);
    });
);

唯一的问题是文本一直被绘制在顶部,所以我的可拖动对象一直在文本后面。我只希望文本保留在背景中,就像静态图像一样,但我认为将字体绘制到画布上可能比让用户下载另一个图像更好。有什么帮助吗?

【问题讨论】:

    标签: javascript html canvas physics-engine matter.js


    【解决方案1】:

    Matter.js 包含的渲染器实际上只是用于演示,所以最好的做法是复制示例 Render.js,然后在那里实现所有渲染(其中 Render.world 是入口方法在每个刻度上调用)。

    将对象名称更改为 CustomRenderer 之类的其他名称,然后在 Engine.create 选项中传递您的渲染类:

    var engine = Engine.create({
        render: {
            element: element,
            controller: CustomRenderer
        }
    });
    

    【讨论】:

      【解决方案2】:

      有点晚了,但文档显示您有正确的方法将精灵添加到渲染器:

          let head = Bodies.circle(450, 50, 17, {
                      render: {
                          sprite: {
                              texture: './img/head.png'
                          }
                      }}
                  );
      

      https://github.com/liabru/matter-js/blob/master/examples/sprites.js

      (还不知道问题的文本部分)

      【讨论】:

        【解决方案3】:

        这是在函数中返回文本字符串作为基础图像的方式

        createImage($string) {
        
            let drawing = document.createElement("canvas");
        
            drawing.width = '150'
            drawing.height = '150'
        
            let ctx = drawing.getContext("2d");
        
            ctx.fillStyle = "blue";
            //ctx.fillRect(0, 0, 150, 150);
            ctx.beginPath();
            ctx.arc(75, 75, 20, 0, Math.PI * 2, true);
            ctx.closePath();
            ctx.fill();
            ctx.fillStyle = "#fff";
            ctx.font = "20pt sans-serif";
            ctx.textAlign = "center";
            ctx.fillText($string, 75, 85);
            // ctx.strokeText("Canvas Rocks!", 5, 130);
        
            return drawing.toDataURL("image/png");
        },
        
        // and then e.g. in your sprites
        
        // ...
        
        render: {
          sprite: {
              texture: createImage("Your Text String")
              xScale: 1,
              yScale: 1
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2017-08-23
          • 1970-01-01
          • 2017-09-28
          • 1970-01-01
          • 1970-01-01
          • 2021-03-21
          • 1970-01-01
          • 2012-07-18
          相关资源
          最近更新 更多