准备工作
<canvas id="scratch" style="width: 800px; height: 500px;"></canvas>
window.onload = function () {
var canvas = document.getElementById("scratch");
// canvas dimensions 画布尺寸
var width = parseInt(canvas.style.width);
var height = parseInt(canvas.style.height);
// retina 视网膜(显示屏)
var dpr = window.devicePixelRatio || 1; //设备像素比
canvas.width = width*dpr;
canvas.height = width*dpr;
canvas.getContext("2d").scale(dpr, dpr); //缩放
/*
* 【正文】才刚刚开始
*/
}
【正文】
// simulation 模拟器
var sim = new VerletJS(width, height, canvas);
sim.friction = 1; //摩擦
// entities 实体
var segment = sim.lineSegments([new Vec2(20, 10)], 0.02);
var pin = segment.pin(0);
/*
* 这里可以添加更多【实体】
*/
// animation loop 动画循环
var loop = function() {
sim.frame(16);
sim.draw();
requestAnimFrame(loop);
};
loop();
【实体】
var tire = sim.tire(new Vec(200, 50), 50, 30, 0.3, 0.9);
var min = Math.min(width, height)*0.5;
var segments = 20;
var cloth = sim.cloth(new Vec2(width/2, height/3), min, min, segments, 6, 0.9);