悠悠球
<html><head>
<meta charset="utf-8">
<script>
$=function(b){return document.getElementById(b)};
Array.prototype.mult=function(d){
var r=[];
for(var i=0;i<this.length;i++){
r.push(d*this[i]);
};
return r;
};
Array.prototype.add=function(v){
for(var i=0;i<this.length;i++){
this[i]+=v[i];
};
return this;
};
Array.prototype.plus=function(v){
var r=[];
for(var i=0;i<this.length;i++){
r.push(v[i]+this[i]);
};
return r;
};
Array.prototype.minus=function(v){
var r=[];
for(var i=0;i<this.length;i++){
r.push(this[i]-v[i]);
};
return r;
};
Array.prototype.norm=function(){
var r=0;
for(var i=0;i<this.length;i++){
r+=this[i]*this[i];
};
return Math.sqrt(r);
};
Array.prototype.unit=function(){
var r=[];
var d=this.norm();
for(var i=0;i<this.length;i++){
r.push(this[i]/d);
};
return r;
};
Array.prototype.rand=function(v){
var r=[];
var max=[];
var min=[];
max.push([this[0],v[0]].max());
min.push([this[0],v[0]].min());
max.push([this[1],v[1]].max());
min.push([this[1],v[1]].min());
r.push(Math.random() * ( max[0] - min[0] ) + min[0]);
r.push(Math.random() * ( max[1] - min[1] ) + min[1]);
return r;
};
Array.prototype.max=function(){
return Math.max.apply({},this)
}
Array.prototype.min=function(){
return Math.min.apply({},this)
}
</script>
</head>
<body>
<canvas id=0 width="270" height="180" style="border:1px solid silver;"></canvas>
<div>
</body>
<script>
var Ball={
s:[0,0],
radius:12,
color:"#6699FF",
fill: function(cxt) {
cxt.save();
cxt.fillStyle = this.color;
cxt.beginPath();
cxt.arc(this.s[0], this.s[1], this.radius, 0, 360 * Math.PI / 180, false);
cxt.closePath();
cxt.fill();
cxt.restore();
}
};
var cnv = $(0);
var cxt = cnv.getContext("2d");
var ball = {s:[cnv.width / 2,cnv.height / 2],__proto__:Ball};
var mouse=[cnv.width / 2,cnv.height / 2];
var spring = 0.02;//弹性系数
var v=[0,0];//速度
var friction = 0.95;//摩擦系数
//定义重力
var gravity = [0,1];//重力加速度
cnv.onmousemove=function(e){
mouse=[e.clientX,e.clientY].minus([this.offsetLeft,this.offsetTop]);
};
(function() {
requestAnimationFrame(arguments.callee);
cxt.clearRect(0, 0, cnv.width, cnv.height);
//加入弹性动画
var a=mouse.minus(ball.s).mult(spring);
//加入重力影响
v.add(a).add(gravity);
v=v.mult(friction);
(ball.s).add(v);
ball.fill(cxt);
//将鼠标以及小球中心连接成一条直线
cxt.beginPath();
cxt.moveTo(ball.s[0], ball.s[1]);
cxt.lineTo(mouse[0], mouse[1]);
cxt.stroke();
cxt.closePath();
})();
</script>
</html>