鼠标移动淡入淡出Canvas小球效果_特炫

4 篇文章 1 订阅

先看效果
在这里插入图片描述

鼠标移动生成不同颜色小球向不同方向以移动

html

<style>
      html,
      body {
          width: 100%;
          height: 100%;
      }
      canvas{
            background: black;
        }
 </style>
<canvas id="canvas"></canvas>

JS

 <script>
        let canvas = document.getElementById('canvas')
        window.onresize = canvasOnresize
        //页面大小改变 canvans大小改变
        function canvasOnresize() {
            canvas.width = document.getElementsByTagName('body')[0].clientWidth
            canvas.height = document.getElementsByTagName('body')[0].clientHeight
        }
        //初始化canvas的高度 宽度 跟随页面的大小
        canvasOnresize()
        //生成小圆
        //初始化画笔
        let ctx = canvas.getContext("2d")
        //装Ball对象的数组
        let ballList = []
        //颜色数组
        let colorList = ["red", "green", "yellow", "blue", "black", "#ccc"]
        function Ball(x, y) {
            this.x = x; //横轴坐标
            this.y = y;//纵轴坐标
            this.color = colorList[Math.floor(this.mathRandom(0, 6))];//随机生成颜色
            this.xv = this.mathRandom(-5, 5);//x轴的分散速度
            this.yv = this.mathRandom(-5, 5);//y轴的分散速度
            this.Alpha1 = 1; //开始透明度
            this.Alpha2 = 0.85;
        }
        //生成小球
        Ball.prototype.update = function () {
            ctx.save();
            ctx.beginPath()
            ctx.fillStyle = this.color// 背景颜色为红色
            ctx.arc(this.x, this.y, 30, 0, Math.PI * 2, false)
            ctx.fill()
            ctx.closePath()
        }
        //小球移动
        Ball.prototype.move = function () {
            this.Alpha1*= this.Alpha2
            ctx.globalAlpha = this.Alpha1 ;
            this.x += this.xv
            this.y += this.yv
        }
        //随机生成 随机数
        Ball.prototype.mathRandom = function (min, max) {
            return (max - min) * Math.random() + min
        }
        // canvas  2  鼠标移动
        canvas.addEventListener('mousemove', function (e) {
                ballList.push(new Ball(e.clientX, e.clientY))  
        })
        //1  触发事件
            changeBall()
        function changeBall() {
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            //循环Ball实例上方法
            ballList.map((item) => {
                item.update()
                item.move()
            })
            //按照电脑最优状态执行定动画效果
            requestAnimationFrame(changeBall)
        }
    </script>
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 19
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六卿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值