canvas制作点击/鼠标移动炫彩小球效果

<script>
    
    const canvas = document.getElementById('myCanvas')
    canvas.setAttribute('width', document.body.clientWidth)
    canvas.setAttribute('height', document.body.clientHeight)
    const ctx = canvas.getContext('2d');
    let ballArr =[]

    // 获取随机颜色
    function getRandomColor() {
        let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'];
        let colorArr = []
        for(let i = 0; i < 3; i++) {
            colorArr.push(arr[parseInt(Math.random() * 16)])
        }
        return `#${colorArr.join('')}`
    }

    // 鼠标移动时效果
    canvas.addEventListener('mouseover', () => {
        canvas.addEventListener('mousemove', (e) => {
            new Ball(e.offsetX, e.offsetY, 15, getRandomColor());
        })
    })

    // 鼠标点击时效果
    canvas.addEventListener('click', (e) => {
        for(let i = 0; i< 20; i++) {
            new Ball(e.offsetX, e.offsetY, i, getRandomColor());
        }
    })

    setInterval(()=> {
        ctx.clearRect(0, 0, document.body.clientWidth, document.body.clientHeight)
        ballArr.forEach(item => {
            item.render();
            item.update()
        })
    }, 10)


    class Ball {
        constructor(x, y, r, color) {
            this.x = x;
            this.y = y;
            this.r = r;
            this.dx = Math.random() * 10 - 5
            this.dy = Math.random() * 10 - 5
            this.color = color;
            ballArr.push(this)
        }

        remove() {
            let index = ballArr.findIndex(item => item === this)
            ballArr.splice(index, 1)
        }

        render() {
            ctx.beginPath();
            ctx.fillStyle = this.color;
            ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
            ctx.fill();
        }
        update() {
            this.r -= .1;
            this.x -= this.dx;
            this.y -= this.dy;
            if(this.r <= 0) {
                this.remove()
                return;
            }
            this.render()
        }
    }
    
</script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值