小圆形从上而下掉落

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>多个圆从上二下掉落</title>
</head>
<body>
    <canvas id="canvas" width="406px" height="300px"></canvas>
</body>
    <script>
       var canvas=document.getElementById("canvas");
       var context=canvas.getContext("2d");//创建画布对象
       var img=new Image();//创建圆心的背景图片
       img.src="bg.png";
        //创建一个圆形对象
        function Circle(){
            this.r=Math.floor(Math.random()*6+5);//圆的半径从5-10
            this.x=Math.random()*(canvas.width-2*this.r+1)+this.r;//横坐标最小值是0+radius,最大值是长度-radius,可以不取整
            this.y=0;
            this.red=parseInt(Math.random()*256);
            this.g=parseInt(Math.random()*256);
            this.b=parseInt(Math.random()*256);
            if(! Circle.prototype.paint) {//在原型对象中添加方法,可以节省内存
                Circle.prototype.paint = function () {
                    //创建路径的方式创建一个圆形
                    context.fillStyle="rgb("+this.red+","+this.g+","+this.b+")";
                    context.beginPath();
                    context.arc(this.x,this.y,this.r,0,Math.PI*2);
                    context.fill();
                }
            }
            if(!Circle.prototype.step){
                Circle.prototype.step=function(){
                    this.y+=10;
                }
            }
        }
        var circles=[];//创建一个放置圆形的数组,数组中是多个圆形对象
       function CreateCircle(){//创建圆形对象
           var circle=new Circle();
           circles.push(circle);//将创建的圆形对象添加到数组中
       }
       function PaintCircle(){//遍历数组对象绘制所有的圆形
           for(var i=0;i<circles.length;i++){
               circles[i].paint();
           }
       }
       function StepCircle() {//遍历数组将所有图形下移
           for(var i=0;i<circles.length;i++){
               circles[i].step();
           }
       }
       var timer=0;
      setInterval(function(){
          timer++;
          //先绘制背景图,再绘制圆,在移动圆,最后继续创建圆
          context.drawImage(img,0,0);
          PaintCircle();
          StepCircle();
          if(timer%5==0){
              CreateCircle();
          }
      },100)
    </script>
</html>

绘制的是圆形自上而下掉落,原来的圆形并没有消失,只是用背景图遮盖了,每一次都是重新绘制,先绘制背景图,后绘制圆形,注意,在绘制的过程中,当背景图片加载结束后,才可以

在上面绘制圆形,否则错误,可以使用onload事件.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值