使用canvas实现一个圆球的触壁反弹

HTML

<canvas id="canvas" width="500" height="500" style="border: 1px solid #FF0000;"></canvas>

JS

1.获取上下文

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

2.实现一个球类

复制代码
 1     class circle {
 2         constructor() {
 3             this.x = 25,
 4             this.y = 25,
 5             this.mx = Math.random()*5,
 6             this.my = Math.random()*3,
 7             this.radius = 25,
 8             this.color = 'blue',
 9             this.draw = function () {
10                 ctx.beginPath();
11                 ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,true);
12                 ctx.fillStyle = this.color;
13                 ctx.fill();
14             }
15         }
16 
17     };
复制代码

3.new一个球

let ball = new circle();

4.实现动画函数

复制代码
    const move = (function () {
        // 清除画布
        ctx.clearRect(0,0, canvas.width, canvas.height);
        
        // 重新绘制圆
        ball.draw();
        
        // 移动圆
        ball.x += ball.mx; // x坐标递增
        ball.y += ball.my; // y坐标递增
        
        // x轴坐标加移动的距离大于画布宽度(到达右边界) 或 x轴坐标加移动的距离等于0(到达左边界) 
        if (ball.x + ball.mx > canvas.width || ball.x + ball.mx < 0) {
            ball.mx = -ball.mx; // x轴坐标递减
        };
        // y轴坐标加移动的距离大于画布宽度(到达下边界) 或 y轴坐标加移动的距离等于0(到达上边界) 
        if (ball.y + ball.my > canvas.height || ball.y + ball.my < 0) {
            ball.my = -ball.my; // y轴坐标递减
        };
        
        // 递归调用当前方法
        window.requestAnimationFrame(arguments.callee);
    })();
复制代码

 

posted @   李文杨  阅读(1161)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示