关键词搜索

源码搜索 ×
×

canvas笔记-绘制运动小球(落地弹起,遇边回弹)

发布2020-05-28浏览1513次

详情内容

程序运行截图如下:

就是这个球,遇到底端及左右两边都可以弹

 

源码如下:

canvas4.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="display: block; margin: 50px auto;">
  9. </canvas>
  10. <script src="js/test4.js"></script>
  11. </body>
  12. </html>

test4.js

  1. ;
  2. const WIDTH = 1024;
  3. const HEIGHT = 768;
  4. const RADIUS = 15;
  5. let ball = {
  6. x: WIDTH / 2,
  7. y: 30,
  8. g: 1.5 + Math.random(),
  9. vx: Math.pow(-1, Math.ceil(Math.random() * 10)) * 4,
  10. vy: -5,
  11. color: '#CC0000'
  12. };
  13. window.onload = function(){
  14. let canvas = document.getElementById("canvas");
  15. let context = canvas.getContext("https://cdn.jxasp.com:9143/image/2d");
  16. contextBuffer.width = WIDTH;
  17. contextBuffer.height = HEIGHT;
  18. canvas.width = WIDTH;
  19. canvas.height = HEIGHT;
  20. render(context, contextTmp);
  21. setInterval(
  22. function(){
  23. render(context, contextTmp);
  24. update();
  25. },
  26. 50
  27. );
  28. }
  29. function update(){
  30. ball.x += ball.vx;
  31. ball.y += ball.vy;
  32. ball.vy += ball.g;
  33. //最顶端不放
  34. if(ball.y > HEIGHT - RADIUS){ //最低端
  35. ball.y = HEIGHT - RADIUS;
  36. ball.vy = -ball.vy * 0.75;
  37. }
  38. if(ball.x < 0 + RADIUS){ //最左端
  39. ball.x = RADIUS;
  40. ball.y = HEIGHT - RADIUS;
  41. ball.vy = -Math.random() * 100 + 30;
  42. ball.vx = Math.random() * 100 + 30;
  43. }
  44. if((WIDTH - RADIUS) - ball.x < 0){ //最右端
  45. ball.x = WIDTH - RADIUS;
  46. ball.y = HEIGHT - RADIUS;
  47. ball.vy = -Math.random() * 100 + 30;
  48. ball.vx = -Math.random() * 100 + 30;
  49. }
  50. }
  51. function render(cxt){
  52. cxt.clearRect(0, 0, WIDTH, HEIGHT);
  53. cxt.fillStyle = ball.color;
  54. cxt.beginPath();
  55. cxt.arc(ball.x, ball.y, 15, 0, 2 * Math.PI);
  56. cxt.closePath();
  57. cxt.fill();;
  58. }

这里只提示几个地方,一个是clearRect()可以清空指定位置的画板。

ball里面的vx指水平方向的速度,vy指垂直方向的速度,g值加速度。

 

 

 

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载