HTML5 canvas 画平抛小球

在这里插入图片描述

<!DOCTYPE html>
<html>
    <head>
        <title>小球平抛运动</title>
    </head>
    <body>
        <canvas id="mycanvas">该浏览器不支持canvas</canvas>
        <script>
            var mycanvas = document.getElementById("mycanvas");
            var ctx = mycanvas.getContext("2d");

            var WIDTH = document.documentElement.clientWidth;
            var HEIGHT = document.documentElement.clientHeight; //这里获取客户端长宽,浏览器大小变化的时候,也随之变换
            mycanvas.width = WIDTH;
            mycanvas.height = HEIGHT;

            //定义一个小球类,包含位置、速度、颜色等信息
            function Ball(x, y, velX, velY, color, size){
                this.x = x;
                this.y = x; 
                this.velX = velX;
                this.velY = velY;
                this.color = color;
                this.size = size;
            }
            var guiji = []; // 记录轨迹坐标
            // 画出小球
            Ball.prototype.draw = function(){
                ctx.clearRect(0, 0, WIDTH, HEIGHT); //清空画布,否则有重影
                ctx.beginPath();
                ctx.fillStyle = this.color;
                ctx.arc(this.x, this.y, this.size, 0, 2*Math.PI);
                ctx.fill();
                drawGuiji();
                guiji.push([this.x, this.y]);
            }
            // 画出小球的移动轨迹
            function drawGuiji(){
                var t1 = guiji.length;
                ctx.moveTo(0, 0);
                ctx.strokeStyle = '#E0E0E0';
                ctx.lineWidth = 1;
                for(i=0; i<t1; i++)
                {
                    ctx.lineTo(guiji[i][0], guiji[i][1]);
                    ctx.stroke();
                }
            }
            // 更新小球的位置,速度等信息
            Ball.prototype.update = function(){
                // 如果撞到地面,就反弹
                if(this.y > HEIGHT)
                {
                    this.velY = -this.velY;
                    this.velX = this.velX - this.velX * 0.005;
                }
                else
                {
                    this.velY = this.velY + 1 - this.velY * 0.01; //加速下落, 考虑了空气阻力,速度越大,阻力越大
                    this.velX = this.velX - this.velX * 0.005;
                }
                this.x = this.x + this.velX;
                this.y = this.y + this.velY;
            }

            // 循环
            var ball = new Ball(0, 0, 8, 0, "red", 15);
            function loop(){
                ball.draw();
                ball.update();
                requestAnimationFrame(loop);
            }

            window.onload = loop;
        </script>
    </body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值