首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用canvas实现一个圆球的触壁反弹

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

作者头像
李文杨
发布2018-03-14 14:40:22
7360
发布2018-03-14 14:40:22
举报

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);
    })();
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档