小气球漂浮

15 篇文章 0 订阅
15 篇文章 0 订阅
<!DOCTYPE html>
<html>


<head>
    <meta charset="utf-8">
    <title>小球</title>
    <style media="screen">
        * {
            margin: 0;
            padding: 0;
        }
    </style>
</head>


<body>
    <canvas id="canvas"></canvas>
</body>
<script type="text/javascript">
    var canvas = document.querySelector("#canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = document.documentElement.clientWidth - 5;
    canvas.height = document.documentElement.clientHeight - 5;


    function Ball() {
        this.radius = this._rand(10, 50);
        this.cx = this._rand(this.radius, canvas.width - this.radius);
        this.cy = this._rand(this.radius, canvas.height - this.radius);
        this.speedX = this._rand(-3, 3);
        this.speedY = this._rand(-3, 3);
        this.color = "rgba(" + this._rand(0, 255) + "," + this._rand(0, 255) + "," + this._rand(0, 255) + "," + Math.random() + ")"
    }
    Ball.prototype.draw = function() {
        ctx.beginPath();
        ctx.arc(this.cx, this.cy, this.radius, 0, 2 * Math.PI);
        ctx.fillStyle = this.color;
        ctx.fill();
    }
    Ball.prototype.move = function() {
        if (this.cx + this.radius >= canvas.width || this.cx - this.radius <= 0) {
            this.speedX *= -1;
        }
        if (this.cy + this.radius >= canvas.height || this.cy - this.radius <= 0) {
            this.speedY *= -1;
        }
        this.cx += this.speedX;
        this.cy += this.speedY;
        this.draw();
    }
    Ball.prototype._rand = function(min, max) {
        return parseInt(Math.random() * (max - min)) + min;
    }
    var balls = [];
    for (var i = 0; i < 100; i++) {
        var ball = new Ball();
        balls.push(ball);
    }
    // setInterval(function(){
    //     ctx.clearRect(0,0,2000,2000);
    //     for(var i=0;i<balls.length;i++){
    //         var ball = balls[i];
    //         ball.move();
    //     }
    // },20)


    function _run() {
        ctx.clearRect(0, 0, 2000, 2000);
        for (var i = 0; i < balls.length; i++) {
            var ball = balls[i];
            ball.move();
        }
        requestAnimationFrame(_run);
    }
    _run();
</script>


</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值