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>

<body>
    <style>
        #canvas {
            border: 1px solid paleturquoise;
        }
    </style>
    <canvas id='canvas'></canvas>
</body>
<script>
    /** @type {HTMLCanvasElement} */
    let canvas = document.querySelector('canvas')
    canvas.width = window.innerWidth - 30
    canvas.height = window.innerHeight - 30
    let ctx = canvas.getContext('2d')
    let speed = 0.8 //速度
    let Friction = 0.9 //摩擦力
    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 = this.color
            ctx.fill()
        }
        this.upload = function () {
            if (this.y + this.radius + this.dy + speed > canvas.height) {
                this.dy = -this.dy
                this.dy *= Friction
            } else {
                this.dy += 0.8
            }
            this.y += this.dy
            this.draw()
        }
    }
    let temparray;
    function init() {
        temparray = []
        for (i = 0; i < 1000; i++) {
            x = Math.random() * canvas.width
            y = Math.random() * canvas.height
            dx = (Math.random() - 0.5 * 2)
            dy = (Math.random() - 0.5 * 2)
            radius = Math.floor(Math.random() * 20)
            r = Math.random() * 255
            g = Math.random() * 255
            b = Math.random() * 255
            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()
        }
    }
    init()
    animate()
    window.addEventListener('mousedown', function () {
        init()
    })
</script>

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