效果如图:

canvas基础绘制-一个小球的坠落、反弹

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<canvas id="canvas" style="border: 1px solid #ddd"></canvas>
<script src="ball.js"></script>
</body>
</html>

ball.js:

var ball = {x:512,y:100,r:20,g:2,vx:10,vy:0,color:"#058"};

window.onload = function () {
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");

    canvas.width = 1024;
    canvas.height = 768;

    setInterval(
        function () {
            update();
            render(context);
        },50)
};

function update() {
    ball.x+=ball.vx;
    ball.y+=ball.vy;
    ball.vy+=ball.g;
}
function render(cxt) {

    cxt.clearRect(0,0,cxt.canvas.width,cxt.canvas.height);

    cxt.fillStyle = ball.color;

    cxt.beginPath();
    cxt.arc(ball.x,ball.y,ball.r,0,2*Math.PI);
    cxt.closePath();

    cxt.fill();
}

小球反弹了:

canvas基础绘制-一个小球的坠落、反弹

ball.js:

//更新
function
update() { ball.x+=ball.vx; ball.y+=ball.vy; ball.vy+=ball.g; if(ball.y>=canvas.height-ball.r){//小球接触底边沿反弹 // ball.vy = -ball.vy*0.5; ball.vy = -ball.vy; }else if(ball.x>=canvas.width-ball.r){ ball.vx = -ball.vx; }else if(ball.x<=ball.r) { ball.vx = -ball.vx; }else if(ball.y<=ball.r){ ball.vy = -ball.vy; } }

 

相关文章:

  • 2021-10-26
  • 2022-02-28
  • 2021-12-02
  • 2021-11-05
  • 2021-04-26
  • 2022-01-23
  • 2021-08-14
猜你喜欢
  • 2021-04-23
  • 2022-12-23
  • 2021-07-16
  • 2022-02-24
  • 2022-01-08
  • 2021-12-20
  • 2021-09-09
相关资源
相似解决方案