其他分享
首页 > 其他分享> > canvas实现碰壁反弹(小球)

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>Document</title>
    <style>
    canvas {
        box-shadow: 0 0 5px red;
        display: block;
        margin: 20px auto;
    }
    </style>
</head>
<body>
    <canvas id="cv" width="800" height="500"></canvas>
    <script>
        var cv = document.querySelector('#cv');
        var ctx = cv.getContext('2d');
        // 不断绘制矩形,矩形坐标通过计时器累加累减
        // x y方向的移动速度不能是同一个
        var x = 0, y = 0, vx = 1, vy = 1;
        setInterval(function(){
            // 清除画布
            ctx.clearRect(0,0,cv.width,cv.height);
            x+=vx;y+=vy;
            ctx.strokeRect(x,y,50,50);
            if(x<=0||x>=cv.width-50){vx*=-1};
            if(y<=0||y>=cv.height-50){vy*=-1};
        },10);
    </script>
</body>
</html>

文章地址  https://www.cnblogs.com/sandraryan/

标签:canvas,小球,ctx,50,var,碰壁,vx,vy,cv
来源: https://www.cnblogs.com/sandraryan/p/11578290.html