Canvas 小球连线-碰壁折返

1. 创建canvas画布

1.1 在body标签内创建canvas标签,并添加id元素。

<canvas id="mycanvas"></canvas>

1.2 在script标签中获取dom元素canvas, 并进行设置,第二行为固定写法。

var canvas = document.querySelector("#mycanvas")
var ctx = canvas.getContext('2d')

1.3 设置画布的宽高分别等于屏幕大小的宽高,宽高分别减10用以呈现完整的画布。

canvas.width = document.documentElement.clientWidth - 10
canvas.height = document.documentElement.clientHeight - 10

1.4 在head头部标签设置画布的样式。 

<style>
    * {
      margin: 0;
      padding: 0;
    }
    canvas {
      display: block;
      margin: 0 auto;
    }
</style>

2. 封装小球的构造函数

    function Ball() {
      this.randomX = Math.ceil(Math.random() * canvas.width)
      this.randomY = Math.ceil(Math.random() * canvas.height)
      this.r = 10
      this.color = 'pink'
      this.dx = Math.ceil(Math.random() * 10) - 5
      this.dy = Math.ceil(Math.random() * 10) - 5

      this.index = ballArr.length
      if (this.randomX < this.r) {
        this.x = this.r
      }else if(this.randomX > canvas.width - this.r) {
        this.x = canvas.width - this.r
      }else {
        this.x = this.randomX
      }

      if (this.randomY < this.r) {
        this.y = this.r
      }else if(this.randomY > canvas.height - this.r) {
        this.y = canvas.height - this.r
      }else {
        this.y = this.randomY
      }

      ballArr.push(this)
    }

2.1  设置生成小球的随机坐标。

      this.randomX = Math.ceil(Math.random() * canvas.width)
      this.randomY = Math.ceil(Math.random() * canvas.height)

根据画布的宽高来随机生成小球x,y的坐标,Math.ceil()为向上取整,也可使用Math.floor()同parseInt()向下取整。

2.2 设置小球的半径及颜色。

      this.r = 10
      this.color = 'pink'

 2.3 设置小球的运动方向。

      this.dx = Math.ceil(Math.random() * 10) - 5
      this.dy = Math.ceil(Math.random() * 10) - 5

生成的数字为1~10之间,需要将生成的数字减5,x轴为负数的球就会往左移动,正数往右;y轴负数往上,正数往下,从而能够达到小球向四面八方运动的一个效果。

2.4 判断小球随机生成的坐标是否让小球在画布之内。

      if (this.randomX < this.r
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值