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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值