Js 面向对象编程 滚动的小球 原型链

本文通过JavaScript实现了一个基于canvas的滚动小球动画,利用面向对象编程和原型链创建了Ball和MoveBall类。在鼠标移动时,会根据鼠标位置随机生成颜色的小球,并让它们按一定规则滚动和缩小。通过setInterval定时更新画布,展示动态效果。
摘要由CSDN通过智能技术生成

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>滚动的小球 原型链</title>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script type="text/javascript">
        let canvas=document.getElementById("canvas");
        let ctx=canvas.getContext("2d");
        canvas.width=1000;
        canvas.height=500;
        canvas.style.backgroundColor="#000";
        // 绘制图形
        function ball(x,y,color){
            this.x=x;//x坐标
            this.y=y;//y坐标
            this.r=40;//半径
            this.color=color;//颜色
        }

        ball.prototype={
            constructor:ball,
            rand(){
                ctx.save();
                ctx.beginPath();//绘制线段
                ctx.arc(this.x,this.y,this.r,0,2*Math.PI);// 绘制圆
                ctx.fillStyle=this.color;
                ctx.fill();//填充路径
                ctx.restore();
            }
        };
        // 单个图形移动 并缩小
        function moveBall(x,y,color){
            this.zx=5-Math.random()*10; //x轴移动的量
            this.zy=5-Math.random()-10;//y轴移动的量
            this.zr=Math.random()*3+1;//r缩小的量
            ball.call(this,x,y,color);
        }
        moveBall.prototype=new ball();
        moveBall.prototype.constructor=moveBall;
        moveBall.prototype.upBall=function(){
                this.x+=this.zx;
                this.y+=this.zy;
                this.r-=this.zr;
                // 当 半径小于0时,要判断
                if(this.r<0){
                    this.r=0;
                }
            }
        let colorArr=['red','blue','yellow','purple','pink','green'];// 生成
        let moveB=[];
        //跟随鼠标随机生成 小圆
        canvas.addEventListener('mousemove',function(e){
            let colorRam=Math.round(Math.random()*(colorArr.length-1));
            moveB.push(new moveBall(e.pageX,e.pageY,colorArr[colorRam]));
        })
        // 添加定时器  每50调用一次
        setInterval(function(){
            // 清除画布
             ctx.clearRect(0,0,1000,500); 
            for (var i = 0; i < moveB.length; i++) {
                moveB[i].rand();
                moveB[i].upBall();
            }
        },50)

    </script>
    
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值