canvas --暴走的小球!!

2016-11-25  本文已影响0人  不爱做饭的码奴就不是合格的猫

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>躁动的小球</title>
<style media="screen">
* {
margin: 0;
padding: 0;
}
html, body {
overflow: hidden;
}
/canvas {
background-color: black;
}
/
</style>
</head>
<body>

    <canvas id="canvas" width="300" height="300">
        <p>您的浏览器不支持cavnas,请<a href="http://www.lidaze.com">点击</a>升级最新版</p>
    </canvas>

</body>
<script type="text/javascript">

    // 工具函数
    function random(min, max) {
        return parseInt(Math.random() * (max - min + 1) + min);
    }
    function randomColor() {
        var r = random(0, 255);
        var g = random(0, 255);
        var b = random(0, 255);
        var a = Math.random() + 0.3;
        return 'rgba('+ r +', '+ g +', '+ b +', '+ a +')';
    }


    // 获取元素
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');

    // 修改canvas的宽高和屏幕一样大小
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    // 获取了canvas的宽高
    var canvasWidth = canvas.width;
    var canvasHeight = canvas.height;


    // 创建小球的构造函数
    function Ball(x, y, r, speedX, speedY, color) {
        this.r = r || random(10, 30);
        this.x = x || random(this.r, canvasWidth - this.r);
        this.y = y || random(this.r, canvasHeight - this.r);

        var sx = random(-5, 5);
        this.speedX = speedX || (sx == 0 ? 1 : sx);

        var sy = random(-5, 5);
        this.speedY = speedY || (sy == 0 ? 1 : sy);

        this.color = color || randomColor();
    }

    // 使用原型添加方法
    Ball.prototype.draw = function () {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
        ctx.closePath();
        ctx.fillStyle = this.color;
        ctx.fill();
    };
    Ball.prototype.move = function () {
        this.x += this.speedX;
        this.y += this.speedY;

        if (this.x <= this.r || this.x >= canvasWidth - this.r) {
            this.speedX *= -1;
        }
        if (this.y <= this.r || this.y >= canvasHeight - this.r) {
            this.speedY *= -1;
        }
    };


    // 创建变量,用于保存所有的小球
    var balls = [];
    // 通过循环,创建对象,并放到数组中
    for (var i = 0; i < 100; i++) {
        var b = new Ball();
        b.draw();
        balls.push(b);
    }



    // 定时器
    setInterval(function () {
        ctx.clearRect(0, 0, canvasWidth, canvasHeight);

        ctx.fillStyle = '#000';
        ctx.fillRect(0, 0, canvasWidth, canvasHeight);

        for (var i = 0; i < balls.length; i++) {
            var b = balls[i];
            b.move();
            b.draw();
        }
    }, 10);

</script>

</html>

上一篇下一篇

猜你喜欢

热点阅读