Canvas制作小球遇边缘反弹

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>小球弹跳</title>
</head>
<body>
    <!-- <img src="222.jpg"> -->
    <canvas id="cvs" width="600" height="500" style="border:1px solid #000;"></canvas>
</body>
<script>
    
    var cvs = document.getElementById("cvs")
    var ctx=cvs.getContext("2d");
    
 
     var x=0,y=0,l=true,z=true;

     setInterval(function(){
         ctx.clearRect(0,0,cvs.width,cvs.height)

        if(l){
            x+=5;
            if(x>=cvs.width-50){
                l=false
            }
        }else{
                x-=5;
                if(x<=50){
                    l=true
                }
            }

        if(z){
            y+=5;
            if(y>=cvs.height-50){
                z=false
            }
        }else{
                y-=5;
                if(y<=50){
                    z=true
                }
            }
     


        // ctx.beginPath()
        // ctx.fillStyle="red"
        // ctx.fillRect(x,y,50,50)
          
        ctx.beginPath(); 
        ctx.arc(x,y,50,0,2*Math.PI);
        ctx.fillStyle="red"
        ctx.closePath(); 
        ctx.fill(); 
        // ctx.stroke();


     },1)

     






</script>
</html>

猜你喜欢

转载自blog.csdn.net/QQ_Empire/article/details/81395199