canvas 粒子效果

效果圖

在這裏插入圖片描述

代碼

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

</head>
<style>
    #canvas {
        border: 1px solid paleturquoise;
    }
</style>

<body>
    <canvas id="canvas"></canvas>
</body>
<script>
    /** @type {HTMLCanvasElement} */
    let canvas = document.getElementById('canvas')
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
    let ctx = canvas.getContext('2d')
    let mousemovexy ={
        x:canvas.width/2,
        y:canvas.height/2
    }
    function Ball(x, y, dx, dy, radius, color) {
        this.x = x,
            this.y = y,
            this.dx = dx,
            this.dy = dy,
            this.radius = radius,
            this.color = color
        this.draw = function () {
            ctx.beginPath()
            ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false)
            ctx.fillStyle = '' + color,
                ctx.fill()
        }
        this.upload = function () {
            if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
                this.dx = -this.dx
            }
            if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
                this.dy = -this.dy
            }
            if(mousemovexy.x-this.x<50 && mousemovexy.x>this.x-50&&mousemovexy.y-this.y<50 && mousemovexy.y>this.y-50){
                this.radius +=1
            }else{
                this.radius = radius
            }
            this.x += this.dx
            this.y += this.dy
            this.draw()
        }
    }
    let temparray = []

    for (let i = 0; i < 1000; i++) {
        let x = Math.random() * canvas.width
        let y = Math.random() * canvas.height
        let dx = (Math.random() - 0.5 * 2)
        let dy = (Math.random() - 0.5 * 2)
        let radius = Math.random() * 4;
        let r = Math.random() * 255
        let g = Math.random() * 255
        let b = Math.random() * 255
        let color = `rgb(${r},${g},${b})`
        temparray.push(new Ball(x, y, dx, dy, radius, color))
    }

    function animate() {
        requestAnimationFrame(animate)
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        for (let b of temparray) {
            b.upload()
        }
    }
    window.addEventListener('mousemove',function(event){
        mousemovexy.x= event.clientX
        mousemovexy.y= event.clientY
    })
    animate()
</script>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章