炫彩小球-canvas

<script setup lang="ts">
import { onMounted } from 'vue';

onMounted(() => {
    init()
})

function init() {
    const myCanvas: HTMLCanvasElement = document.getElementById("main_canvas") as HTMLCanvasElement
    const ctx = myCanvas.getContext("2d")

    let ballArr: Ball[] = []
    class Ball {
        color: string
        r: number
        dx: number
        dy: number
        constructor(public x: number, public y: number) {
            this.color = this.getRandomColor()
            this.r = Math.floor(Math.random() * 100 + 1)    //半径【1,100】
            this.dx = Math.floor(Math.random() * 10) - 5
            this.dy = Math.floor(Math.random() * 10) - 5
        }
        //随机颜色
        getRandomColor(): string {
            let allType = '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f'
            let allTypeArr = allType.split(',')
            let color = '#'
            for (let index = 0; index < 6; index++) {
                let randomNum = Math.floor(Math.random() * allTypeArr.length)
                color = color + allTypeArr[randomNum]
            }
            return color
        }
        //渲染小球
        render(): void {
            if (ctx !== null) {
                ctx.beginPath()
                ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false)
                ctx.fillStyle = this.color
                ctx.fill()
            }
        }
        //更新小球
        update(): void {
            this.x = this.x + this.dx
            this.y = this.y + this.dy
            this.r = this.r - 0.5
            if (this.r <= 0) {
                this.remove()
            }
        }

        //移除小球
        remove(): void {
            for (let index = 0; index < ballArr.length; index++) {
                const element = ballArr[index];
                if (element == this) {
                    ballArr.splice(index, 1)
                }

            }
        }
    }

    //监听鼠标的事件
    myCanvas.addEventListener('mousemove', (event) => {
        ballArr.push(new Ball(event.offsetX, event.offsetY))
    })

    //定时器动画渲染和更新
    setInterval(() => {
        if (ctx !== null) {
            //先清空
            ctx.clearRect(0, 0, 500, 500)
        }
        for (let index = 0; index < ballArr.length; index++) {
            const element = ballArr[index];
            element.update()
            if (element) {
                element.render()
            }
        }
    }, 1000 / 60)
}

</script>
<template>
    <canvas width="1000" height="800" id="main_canvas"></canvas>
</template>
<style scoped></style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值