1. 程式人生 > >JS+canvas畫個小球,利用正弦函式使小球上下移動

JS+canvas畫個小球,利用正弦函式使小球上下移動


<body>
<canvas id="canvas" width="500" height="500" style="border:dashed 1px"></canvas>
</body>
<script>
var canvas = document.getElementById('canvas');
var ctx=canvas.getContext('2d');
function ball() {
this.r = 14;
this.x = canvas.width/2;
this.y = canvas.height/2;
this.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
ctx.stroke();
};
};
var ball=new ball();//建立小球例項

ball.draw();//畫個小球
var speed=0.1;//弧度每次增加的量,試著改變該數值,小球運動會增大哦
var angle=0;//小球的弧度,下面要用到
function ballMove(){
ctx.clearRect(0,0,500,500);//每次呼叫該方法,先清除畫布,重新畫小球。
//Math.sin(angle)的結果是-1到1,乘以50 是小球的y座標從-50到50
ball.y=canvas.height/2+Math.sin(angle)*50;     
angle+=speed
ball.draw();
  }
setInterval(ballMove,100)//計時器,每100毫秒呼叫一次ballMove函式
</script>