Member-only story
Physics of text using Matter.js
Matter.js is one of the libraries for physics

Background
There were several libraries for arithmetic processing of squares, circles, and other shapes, but I couldn’t find a sample with text, so I’m going to research and post it as a reminder. As for the library selection, there were several libraries for physical operations, but I’m using Matter.js, which is lightweight and smartphone-compatible.
Custom Render
Matter.js uses a default render for displaying shapes. If you add a Body object to the **world**, this render will automatically display the body along with the physics operations. However, this default render does not support text display. Instead, you are instructed to use Custom Render, which seems to be a way to draw the body in the Canvas by itself using the calculated body information.
Normally the render is used as follows.
const Engine = Matter.Engine
const Render = Matter.Render
const engine = Engine.create()
const render = Render.create({
element: document.getElementById('app'),
engine: engine,
options: {
wireframes: false,
width: 300,
height: 400,
background: 'rgba(255, 0, 0, 0.5)'
}
})Render.run(render)
Instead of this Render, we draw it ourselves. The bodies we get in `Matter.Composite.allBodies(this.engine.world)` contains the Body information (such as coordinate information) as a result of the physics calculation.
this.render()render () {
// NOTE: Retrieve all Body elements added to the World
const bodies = Matter.Composite.allBodies(this.engine.world)
const canvas = document.getElementById('canvas')
const context = canvas.getContext('2d')
window.requestAnimationFrame(this.render)
// NOTE: Draw a square by connecting the point coordinates
// (or 4 vertices in the case of a rectangle) in a body element. for (let i = 0; i < bodies.length; i += 1) {
const part = bodies[i]
const vertices = bodies[i].vertices
context.moveTo(vertices[0].x, vertices[0].y)
for (var j = 1; j < vertices.length; j += 1) {
context.lineTo(vertices[j].x, vertices[j].y)
} context.lineTo(vertices[0].x, vertices[0].y)
}