【前端html/js】canvas的小球弹性案例

【前端html/js】canvas的小球弹性案例

案例效果

  • 代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>弹性运动升级版</title>
  <style>
    *{margin: 0;padding: 0;box-sizing: border-box;overflow: hidden;}
  </style>
</head>
<body>
  <canvas id="canvas" ></canvas>
<script>
  let canvas = document.getElementById('canvas');
  const [width,height] = [window.innerWidth,window.innerHeight];
  canvas.setAttribute('width',width);
  canvas.setAttribute('height',height);
  let ctx = canvas.getContext('2d');


  class B {
    constructor(r=30,color="#edd2cb") {
      this.r=r;
      this.color=color;
      this.x=0;
      this.y=0
    }
    draw(ctx){
      ctx.save();
      ctx.beginPath();
      ctx.strokeStyle=this.color;
      ctx.fillStyle=this.color;
      ctx.arc(this.x,this.y,this.r,0,Math.PI*2);
      ctx.stroke();
      ctx.fill();
      ctx.closePath();
      ctx.restore();
    }
  }

  //弹性运动
  let a = new B(80);
  a.x = width/2;
  a.y=a.r*2.2 ;

  // 速度毫秒
  let lx = 0.1;
  let ly = 0.1;

  // 重力 gravity
  const gravity=0.01;

  // 弹力
  let bounce = 0.8;
  let time = new Date();

  !(function render(){
    ctx.clearRect(0,0,width,height);
    let now = new Date();
    let diff = now - time;
    time = now;

    ly += gravity;
    a.y += ly * diff;
    a.x += lx * diff;

    // 底部
    if(a.y+a.r>height){
      a.y = height - a.r;
      ly *= -bounce;
    }
    // 右侧
    if(a.x+a.r>width){
      a.x = width - a.r;
      lx *= -bounce;
    }
    // 左侧
    if(a.x-a.r<0){
      a.x =  a.r;
      lx *= -bounce;
    }

    a.draw(ctx);
    requestAnimationFrame(render)
  })();

  window.addEventListener("visibilitychange",()=>{
    time=new Date();
  })

</script>
</body>
</html>

github

写于:2022年1月15日
作者QQ:420318184
邮箱:fy@0fy0.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飛之宇

你的支持是我们的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值