var canvas = document.getElementById("scratch");
var width = parseInt(canvas.style.width);
var height = parseInt(canvas.style.height);
var dpr = window.devicePixelRatio || 1;
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.getContext("2d").scale(dpr, dpr);
var sim = new VerletJS(width, height, canvas);
sim.highlightColor = "#fff";
var min = Math.min(width, height) * 0.5;
var cloth = sim.cloth(new Vec2(width / 2, height / 3), min, min, segments, 6, 0.9);
cloth.drawConstraints = function (ctx, composite) {
var stride = min / segments;
for (y = 1; y < segments; ++y) {
for (x = 1; x < segments; ++x) {
var i1 = (y - 1) * segments + x - 1;
var i2 = (y) * segments + x;
ctx.moveTo(cloth.particles[i1].pos.x, cloth.particles[i1].pos.y);
ctx.lineTo(cloth.particles[i1 + 1].pos.x, cloth.particles[i1 + 1].pos.y);
ctx.lineTo(cloth.particles[i2].pos.x, cloth.particles[i2].pos.y);
ctx.lineTo(cloth.particles[i2 - 1].pos.x, cloth.particles[i2 - 1].pos.y);
var off = cloth.particles[i2].pos.x - cloth.particles[i1].pos.x;
off += cloth.particles[i2].pos.y - cloth.particles[i1].pos.y;
var coef = Math.round((Math.abs(off) / stride) * 255);
if (coef > 255) coef = 255;
ctx.fillStyle = "rgba(" + coef + ",0," + (255 - coef) + "," + lerp(0.25, 1, coef / 255.0) + ")";
for (c in composite.constraints) {
if (composite.constraints[c] instanceof PinConstraint) {
var point = composite.constraints[c];
ctx.arc(point.pos.x, point.pos.y, 1.2, 0, 2 * Math.PI);
ctx.fillStyle = "rgba(255,255,255,1)";
cloth.drawParticles = function (ctx, composite) {