<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>
炫彩小球-canvas
最新推荐文章于 2024-11-10 15:10:09 发布