Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Created September 4, 2017 19:21
Show Gist options
  • Save joduplessis/4d807823a913e1507d557e0fd3f3a1f4 to your computer and use it in GitHub Desktop.
Save joduplessis/4d807823a913e1507d557e0fd3f3a1f4 to your computer and use it in GitHub Desktop.
Example of using MatterJS to draw a cirlce on a canvas.
function init() {
// Matter.js module aliases
let Engine = Matter.Engine,
World = Matter.World,
Composites = Matter.Composites,
Bodies = Matter.Bodies;
// Particle options
let particleOptions = {
friction: 0.05,
frictionStatic: 0.1,
render: { visible: true }
};
// Create a Matter.js engine
let engine = Engine.create(document.body);
// Create two boxes and a ground
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
let circleX = 300;
let circleY = 300;
let circleR = 100;
let circleA = 0;
let circleI = 2;
// Holder for all our objects
let objectArray = [];
while (circleA<360) {
// Get the XY values of the point
let x = circleX + circleR * Math.cos(circleA);
let y = circleY + circleR * Math.sin(circleA);
// Draw the point
drawPoint(x, y);
// Increase the angle
circleA += circleI;
// Testing the output
objectArray.push(Bodies.rectangle(x, y, 10, 10));
}
// Add the ground
objectArray.push(Bodies.rectangle(400, 610, 810, 60, { isStatic: true }));
objectArray.push(Composites.softBody(250, 400, 2, 2, 0, 0, true, 10, particleOptions));
// Add all of the bodies to the world
World.add(engine.world, objectArray);
// Run the engine
Engine.run(engine);
// Draw a static point
function drawPoint(px, py) {
context.beginPath();
context.arc(px, py, 2, 0, 2 * Math.PI, true);
context.fill();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment