Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matter.js: placing text or images on the canvas

I'm wanting to place font or static images onto the canvas but not sure what the best approach is using Matter.js. Right now, for images, i'm just creating a body with a size of '0' and putting the image url in the render.sprite.texture property. Seems to do the trick but is there a different/better way of putting static images on the canvas?

Also, I am putting text onto the canvas using the 'afterRender' event near the top of my scripts, before anything else is created/drawn:

_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);
    });
);

Only problem is the text keeps getting drawn on top so my draggable objects keep going behind the text. I just want the text to stay in the background, like a static image, but I figured drawing the font onto the canvas might be better than having to make the user download another image. Any help?

like image 352
HaulinOats Avatar asked Sep 25 '14 16:09

HaulinOats


2 Answers

The renderer included with Matter.js is really only intended for demonstration, so the best thing to do is make a copy of the example Render.js and then implement all of your rendering there (where Render.world is the entry method called on each tick).

Change the object name to something else like CustomRenderer, then pass your render class through in the Engine.create options:

var engine = Engine.create({
    render: {
        element: element,
        controller: CustomRenderer
    }
});
like image 174
liabru Avatar answered Sep 27 '22 02:09

liabru


A little late, but the documentation for this shows you had the correct method in adding the sprite to the renderer:

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

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

(No idea about the text part of the question, yet)

like image 35
Robbie Avatar answered Sep 25 '22 02:09

Robbie