html5 spring demo

时间:2022-03-02 14:39:50
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Follow Mouse</title>
<script type="text/javascript" src="utils.js"></script>
<script type="text/javascript" src="ball.js"></script>
<style type="text/css">
body{background-color: silver;}
#canvas{background-color: white;}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<textarea name="" id="log" cols="30" rows="10"></textarea>
<script type="text/javascript">
window.onload=function(){
var canvas=document.getElementById("canvas"),
context=canvas.getContext("2d"),
mouse=utils.captureMouse(canvas),
ball=new Ball(),
spring=0.03,
friction=0.9,
gravity=2,
vx=0,
vy=0;
(function drawFrame(){
window.requestAnimationFrame(drawFrame,canvas);
context.clearRect(0,0,canvas.width,canvas.height); var dx=mouse.x-ball.x,
dy=mouse.y-ball.y,
ax=dx*spring,
ay=dy*spring;
vx+=ax;
vy+=ay;
vy+=gravity;
vx*=friction;
vy*=friction;
ball.x+=vx;
ball.y+=vy;
context.beginPath();
context.moveTo(ball.x,ball.y);
context.lineTo(mouse.x,mouse.y);
context.stroke();
ball.draw(context); }())
}
</script>
</body>
</html>
utils.js 文件 https://gist.github.com/King-fly/6034511/raw/2e28359afdfb45800948f0e6bd31aa958ba7f5cb/html5+utilsball.js 文件 https://gist.github.com/King-fly/6034525/raw/4664959f6e33196b9b4520136cc67573e07c8282/ball.js