1. 程式人生 > >canvas實現跳動的小球

canvas實現跳動的小球

canvas實現主要程式碼

canvas(centerx,centery,radius,startingAngle,endingAngle,antclockwise=false)

canvas(x軸座標,y軸座標,角度,開始的角度,結束的角度,順時針(預設false)/逆時針true)

角度從0開始,一整個圓結束是2PI

demo程式碼

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>跳動的小球</title>
</head>
<body>
<canvas id="canvas" style="display:block;margin: 0 auto;border: 1px solid black">
    當前瀏覽器不支援canvas,請更換瀏覽器再試
</canvas>
<script>
    var ball={x:712,y:100,r:20,g:2,vx:-4,vy:-10,color:'red'} //定義球的初始值g:加速度,vx:x軸方向的速度,vy:y軸方向的速度
    window.onload=function(){
        var canvas=document.getElementById('canvas')
        canvas.width=1024;
        canvas.height=768;
        var context=canvas.getContext('2d') //環境
        setInterval(function(){
            render(context)
            update()
        },50)
    }

    function render(cxt){
        cxt.clearRect(0,0,cxt.canvas.width,cxt.canvas.height)
        cxt.beginPath()
        cxt.arc(ball.x,ball.y,ball.r,0,2*Math.PI)
        cxt.fillStyle=ball.color
        cxt.fill()   //填充
    }
    function update(){
        ball.x+=ball.vx
        ball.y+=ball.vy
        ball.vy+=ball.g
        if(ball.y>=768-ball.r){
            ball.y=768-ball.r
            ball.vy=-ball.vy*0.5  //到達底部彈起來,*0.5有個緩衝的效果
        }
    }

</script>
</body>
</html>