Skip to content

Instantly share code, notes, and snippets.

View anuraghazra's full-sized avatar
:electron:
Learning

Anurag Hazra anuraghazra

:electron:
Learning
View GitHub Profile
let canvas = document.getElementById('c');
let ctx = canvas.getContext('2d');
let width = canvas.width = 800;
let height = canvas.height = 600;
let verly = new Verly(16);
let cloth = verly.createCloth(150, 150, 250, 250, 15, 2);
function animate() {
ctx.clearRect(0, 0, width, height);
let box = new Entity(100);
// x, y, vx, vy added random velocity in first dot to make the box rotate a little bit
box.addDot(100, 100, (Math.random() - 0.5) * 100.0);
box.addDot(200, 100);
box.addDot(200, 200);
box.addDot(100, 200);
box.addStick(0, 1);
box.addStick(1, 2);
box.addStick(2, 3);
class Entity {
constructor(iterations) {
this.dots = [];
this.sticks = [];
this.iterations = iterations || 16;
}
addDot(x, y, vx, vy) {
this.dots.push(new Dot(x, y, vx, vy));
}
const ITERATION = 100; // max physics iterations per frame
function animate() {
ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
// update
for (let i = 0; i < ITERATION; i++) {
for (let d of dots) {
d.constrain();
let canvas = document.getElementById("c");
let ctx = canvas.getContext("2d");
let CANVAS_WIDTH = window.innerWidth;
let CANVAS_HEIGHT = window.innerHeight;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
// arrays
let dots = [];
let sticks = [];
let canvas = document.getElementById("c");
let ctx = canvas.getContext("2d");
let CANVAS_WIDTH = window.innerWidth;
let CANVAS_HEIGHT = window.innerHeight;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
let dots = [];
for (let i = 0; i < 50; i++) {
render(ctx) {
ctx.beginPath();
ctx.strokeStyle = this.color;
ctx.moveTo(this.startPoint.pos.x, this.startPoint.pos.y);
ctx.lineTo(this.endPoint.pos.x, this.endPoint.pos.y);
ctx.stroke();
ctx.closePath();
}
update() {
// calculate the distance between two dots
let dx = this.endPoint.pos.x - this.startPoint.pos.x;
let dy = this.endPoint.pos.y - this.startPoint.pos.y;
// pythagoras theorem
let dist = Math.sqrt(dx * dx + dy * dy);
// calculate the resting distance betwen the dots
let diff = (this.length - dist) / dist * this.stiffness;
// getting the offset of the points
class Stick {
constructor(p1, p2, length) {
this.startPoint = p1;
this.endPoint = p2;
this.stiffness = 2;
this.color = '#f5476a';
// if the length is not given then calculate the distance based on position
if (!length) {
this.length = this.startPoint.pos.dist(this.endPoint.pos);
constrain() {
if (this.pos.x > CANVAS_WIDTH - this.radius) {
this.pos.x = CANVAS_WIDTH - this.radius;
}
if (this.pos.x < this.radius) {
this.pos.x = this.radius;
}
if (this.pos.y > CANVAS_HEIGHT - this.radius) {
this.pos.y = CANVAS_HEIGHT - this.radius;
}