canvas实现多个弹跳小球 js部分

// 获取class名为picture的canvas元素
        var can = document.querySelector('.picture');
        // 让它撑满整个屏幕
        can.width = window.innerWidth;
        can.height = window.innerHeight;
        // 获取2d上下文
        ctx = can.getContext('2d');
        // 封装一个类

        ; (function (win) {
            function Circle() {
                if (!(this instanceof Circle)) {
                    return new Circle();
                }
                this.x = ran(win.innerWidth);//圆心x轴坐标
                this.y = ran(win.innerHeight);//圆心y轴坐标
                this.r = ran(20);//半径
                this.vx = ran(10);//速度
                this.vy = ran(10);//速度
                this.color = Mock.random.color();//mock.js中的随机颜色api
            }
            Circle.prototype = {
                constructor: Circle,

                //画画函数
                draw: function (ctx) {
                    ctx.beginPath();
                    ctx.arc(this.x, this.y, this.r, 0, 360, true);
                    ctx.fillStyle = this.color;
                    ctx.fill();
                    ctx.closePath();
                },
                // 小球的边界判定函数(回弹)
                move: function (ctx) {
                    var canvasWidth = ctx.canvas.width;
                    var canvasHeight = ctx.canvas.height;
                    //判断4个边
                    if (this.y > (canvasWidth - this.r) || this.y < this.r) {
                        this.vy = -this.vy;
                    }
                    if (this.x > (canvasHeight - this.r) || this.x < this.r) {
                        this.vx = -this.vx;
                    }
                    //偏移量
                    this.x += this.vx;
                    this.y += this.vy;
                },
                // 随机数函数
                ran: function (Num) {
                    return Math.floor(Math.random() * Num);
                }
            }
            //暴露接口
            win.Circle = Circle;
        }(window));


        //调用20次(20和小球同时运动)
        var arr = [];
        for (var i = 0; i < 20; i++) {
            arr.push(Circle())
        }

        function draw() {
            // 清楚之前的画布
            ctx.clearRext(0, 0, window.innerWidth, window.innerHeight);

            for (var i = 0; i < arr.length; i++) {
                var circle = arr[i];
                circle.move(ctx);//调用Circle类中的move方法
                circle.draw(ctx);//调用Circlr类中的draw方法

            }
            requestAnimationFrame(draw)//动画函数 递归调用draw函数
        }
        draw();//首次调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值