Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 26 additions & 7 deletions Cloth.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ window.requestAnimFrame =
window.setTimeout(callback, 1e3 / 60)
}

const defaultGravity = 400
let accuracy = 5
let gravity = 400
let gravity = defaultGravity
let clothY = 28
let clothX = 54
let spacing = 8
Expand All @@ -20,8 +21,8 @@ let bounce = 0.5
let canvas = document.getElementById('canvas')
let ctx = canvas.getContext('2d')

canvas.width = window.innerWidth
canvas.height = window.innerHeight
canvas.width = Math.min(700, window.innerWidth)
canvas.height = 400

ctx.strokeStyle = '#555'

Expand Down Expand Up @@ -170,15 +171,15 @@ class Constraint {
}

class Cloth {
constructor () {
constructor (free) {
this.points = []

let startX = canvas.width / 2 - clothX * spacing / 2

for (let y = 0; y <= clothY; y++) {
for (let x = 0; x <= clothX; x++) {
let point = new Point(startX + x * spacing, 20 + y * spacing)
y === 0 && point.pin(point.x, point.y)
!free && y === 0 && point.pin(point.x, point.y)
x !== 0 && point.attach(this.points[this.points.length - 1])
y !== 0 && point.attach(this.points[x + (y - 1) * (clothX + 1)])

Expand Down Expand Up @@ -220,13 +221,31 @@ canvas.onmousedown = (e) => {

canvas.onmousemove = setMouse

canvas.onmouseup = () => (mouse.down = false)
window.onmouseup = () => (mouse.down = false)

canvas.oncontextmenu = (e) => e.preventDefault()

let cloth = new Cloth()

;(function update (time) {
function zeroG() {
if(gravity === 0){
gravity = defaultGravity
cloth = new Cloth(false)
} else {
gravity = 0
cloth = new Cloth(true)
}
}

function reset(){
if(gravity === 0){
cloth = new Cloth(true)
} else {
cloth = new Cloth(false)
}
}

(function update (time) {
ctx.clearRect(0, 0, canvas.width, canvas.height)

cloth.update(0.016)
Expand Down
6 changes: 5 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<!--

It's been a couple of years since I made the original tearable cloth, and since then both me and Javscript have improved. I thought it deserved an update.
It's been a couple of years since I made the original tearable cloth, and since then both me and Javascript have improved. I thought it deserved an update.

It should be more efficient, wall collisions are greatly improved, and it has a slightly more stretchy, cloth-like texture. The code is better, a bit smaller and now in ES2015.

Expand All @@ -12,3 +12,7 @@
<a href="https://github.com/Dissimulate/Tearable-Cloth">Github</a>
<a href="https://twitter.com/abro_oks">@abro_oks</a>
</div>
<div>
<button onclick="zeroG()">Zero G!</button>
<button onclick="reset()">Reset</button>
</div>