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
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);
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
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();
}
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++) {
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 = [];
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();
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));
}
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);
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);
@anuraghazra
anuraghazra / index.html
Created November 5, 2019 07:18
Testing Gist API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Gist</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>