HTML5实现随机生成小球并向上移动

这篇博客展示了如何使用 HTML5 的 canvas 元素和 JavaScript 实现一个随机生成彩色小球并让它们向上移动的效果。通过创建 Ball 类,定义其位置、颜色和绘制方法,结合定时器动态添加和更新小球的位置,实现了动态飘动的视觉效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<html>
<head>
<title>飘动小球</title>
<style>
    form {
        background-color: yellow;
    }
</style>
<script>
    var ctx;
    var g=2;
    var balls=[];
    function Ball(bx,by,rad,color){
        this.bx = bx;
        this.by = by;
        this.rad = rad;
        this.fillStyle = color;
        this.draw = drawball;
    }
    function drawball(){
        ctx.fillStyle = this.fillStyle;
        ctx.beginPath();
        ctx.arc(this.bx,this.by,this.rad,0,Math.PI*2,true);
        ctx.fill();
    }
    
    function init(){
        ctx = document.getElementById('canvas').getContext('2d');
        setInterval(creat,100);
    }
    function drawall(){
        ctx.clearRect(0,0,600,600);
        
        var i;
        for (i=0;i<balls.length;i++){
            balls[i].draw();
        }
        ctx.strokeRect(0,0,600,600);
    }
    function creat(){
        var col = 'rgb('+ Math.floor(Math.random()*256) + ','+ 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值