查看: 849|回复: 0

[DIV/CSS] canvas基础绘制-一个小球的坠落、反弹

发表于 2017-9-24 08:00:05
尚学堂AD

效果如图:

html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <canvas id="canvas" style="border: 1px solid #ddd"></canvas>
  9. <script src="ball.js"></script>
  10. </body>
  11. </html>
复制代码

ball.js:

  1. var ball = {x:512,y:100,r:20,g:2,vx:10,vy:0,color:"#058"};
  2. window.onload = function () {
  3. var canvas = document.getElementById("canvas");
  4. var context = canvas.getContext("2d");
  5. canvas.width = 1024;
  6. canvas.height = 768;
  7. setInterval(
  8. function () {
  9. update();
  10. render(context);
  11. },50)
  12. };
  13. function update() {
  14. ball.x+=ball.vx;
  15. ball.y+=ball.vy;
  16. ball.vy+=ball.g;
  17. }
  18. function render(cxt) {
  19. cxt.clearRect(0,0,cxt.canvas.width,cxt.canvas.height);
  20. cxt.fillStyle = ball.color;
  21. cxt.beginPath();
  22. cxt.arc(ball.x,ball.y,ball.r,0,2*Math.PI);
  23. cxt.closePath();
  24. cxt.fill();
  25. }
复制代码

小球反弹了:

ball.js:

  1. //更新<br>function update() {
  2. ball.x+=ball.vx;
  3. ball.y+=ball.vy;
  4. ball.vy+=ball.g;
  5. if(ball.y>=canvas.height-ball.r){//小球接触底边沿反弹
  6. // ball.vy = -ball.vy*0.5;
  7. ball.vy = -ball.vy;
  8. }else if(ball.x>=canvas.width-ball.r){
  9. ball.vx = -ball.vx;
  10. }else if(ball.x<=ball.r) {
  11. ball.vx = -ball.vx;
  12. }else if(ball.y<=ball.r){
  13. ball.vy = -ball.vy;
  14. }
  15. }
复制代码



回复

使用道具 举报