canvas制作框内跳动小球

效果如下:
在这里插入图片描述
思路:
1.制定画布,确定好坐标
2.绘制出圆形小球
3.给圆一个原始坐标,xy轴的速度
4.每20毫秒刷新一次,达到变化的目的
5.判断边缘

全部代码及释义如下:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <canvas id="canvas" style="border:1px solid #aaa;display:block;margin: 50px auto;">
    当前浏览器不支持canvas,请更新浏览器或者升级浏览器后再试
  </canvas>

  <script>
    // x: 小球原始x坐标,y: 小球原始y坐标, r: 小球半径, vx: x轴速度,vy: y轴的速度 (速度都以向量表示,所以可为负数)
    var ball = { x: 512, y: 100, r: 20, vx: -8, vy: 8, color: '#005588' }
    window.onload = function () {
      var canvas = document.getElementById("canvas");

      // 制定canvas画布的大小
      canvas.width = 860;
      canvas.height = 600;
      // 判断浏览器是否支持canvas
      if (canvas.getContext("2d")) {
        // 下面所有调用的函数都是基于context这个上下文环境来进行的
        var context = canvas.getContext("2d");

        setInterval(() => {
          render(context)
          update()
        }, 20);
      } else {
        alert("当前浏览器不支持canvas,请更新浏览器或者升级浏览器后再试");
      }
    };
    //十六进制颜色随机
    function color16() {
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      var color = '#' + r.toString(16) + g.toString(16) + b.toString(16);
      return color;
    }
    // 小球的坐标的刷新
    function update() {
      ball.x += ball.vx // x轴坐标 vx是x轴的速度,匀速增加
      ball.y += ball.vy  // y轴坐标 由于g的原因,速度是匀变速
      
      // 触底的条件
      if (ball.y >= canvas.height - ball.r) {
        ball.color = color16()
        ball.y = canvas.height - ball.r    // 触下底
        ball.vy = -ball.vy
      } else if (ball.x <= ball.r) {
        ball.color = color16()
        ball.x = ball.r // 触左
        ball.vx = -ball.vx
      } else if (ball.x >= canvas.width - ball.r) {
        ball.color = color16()
        ball.x = canvas.width - ball.r  // 触右
        ball.vx = - ball.vx
      } else if (ball.y <= ball.r) {
        ball.color = color16()
        ball.y = ball.r   // 触上
        ball.vy = -ball.vy
      }
    }
    // 绘制圆形小球
    function render(cxt) {
      // 利用clearRect,清空画布
      cxt.clearRect(0, 0, cxt.canvas.width, cxt.canvas.height)

      cxt.fillStyle = ball.color
      cxt.beginPath()
      //context.arc(圆心横坐标, 原型纵坐标, 半径的长度,绘制的起点, 绘制的终点)
      cxt.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI)
      cxt.closePath()

      cxt.fill()
    }
  </script>
</body>

</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值