canvas画布内实现小球的随机移动

 引用原文章:原文链接 

效果图 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        canvas {
            border:1px solid #daf;
        }
    </style>
</head>
<body>
<canvas id="game" width="500" height="500"></canvas>

</body>
<script>
//创建球构造函数
function ball() {
    this.r = this.rand(20);
    this.x = this.r;
    this.y = this.r;
    this.speedX = this.rand(10);
    this.speedY = this.rand(10);
    this.width = 0;
    this.height = 0;
    this.canvas = {};
    this.color = 'rgb('+this.rand(255)+','+this.rand(255)+','+this.rand(255)+')';
    this.init();
}
//2.向原型链添加方法
ball.prototype = {
    init:function () {
        var game = document.getElementById('game');
        this.canvas = game.getContext('2d');
        this.width=game.width;
        this.height=game.height;
    },
    rand:function (num) {
        return Math.floor(Math.random() * num+1);
    },
    play:function () {
        this.x += this.speedX;
        this.y += this.speedY;
        if (this.x>this.width-this.r) {
            this.speedX = -this.speedX;
        }
        if (this.x<this.r) {
            this.speedX = Math.abs(this.speedX);
        }
        if (this.y>this.width-this.r) {
            this.speedY = -this.speedY;
        }
        if (this.y<this.r) {
            this.speedY = Math.abs(this.speedY);
        }
        this.canvas.beginPath();
        this.canvas.fillStyle = this.color;
        this.canvas.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
        this.canvas.fill();
    }
};
//3.创建100个小球
var arr = [];
for (var i=0;i<100;i++) {
    arr[i] = new ball();
}

//4.使用定时器,每个30ms刷新屏幕
setInterval(function () {
    arr[0].canvas.clearRect(0,0,500,500);
    for (var i=0;i<arr.length;i++) {
        arr[i].play();
    }
},20)
</script>
</html>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值