简体   繁体   中英

How to make multiple elements in a canvas

I'm trying to show multiple pipes in the canvas of same height but even after using a for loop it is showing a single pipe and not a lot of it

<script>
    var tryCanvas = document.getElementById("myCanvas");
    var c = tryCanvas.getContext("2d");
    var myCall = [];

    function Squares() {

        for(var i =0; i < 10; i++){
            this.x = Math.random()* tryCanvas.clientWidth;
            this.y = 0;
            this.w = 20;
            this.h = 60;
            this.counter = 0;
            this.draw = function() {
                c.beginPath();
                c.rect(this.x, this.y, this.w, this.h)
                c.fill();
            }
    }

        this.update = function() {
            if(this.x < 0){
                this.x = 0;
            }
            this.x -= 1;
            this.draw();
        }
    }

    var holder = new Squares;

    setInterval(callFun, 10);

       function callFun() {
        c.clearRect(0,0,tryCanvas.clientWidth, tryCanvas.clientHeight);
        holder.update();    
       }
 </script>

If I push the constructor function in an array it's not showing anything in the canvas and in the console it's giving undefined or NaN. But if I do it without "this" its generating the number of rects. What am I doing wrong here?

Updated to move the bars along the screen

See this working example: https://codepen.io/bkfarns/pen/braWQB?editors=1010

This.draw will only get created with the values from the last iteration of the for loop.

Also as a side node, usually instead of new Squares you call the constructor like new Squares() . When you call the constructor you are calling a method.

But I think the code below fixes your issues. Try it out:

<body>
  <canvas id="myCanvas"/>
</body>

<script>
    var tryCanvas = document.getElementById("myCanvas");
    var c = tryCanvas.getContext("2d");
    var myCall = [];

    function Squares() {

        this.draw = function(xOffset) {

          for(var i =0; i < 10; i++){

            this.x = (i * xOffset) + (5*i)//Math.random()* tryCanvas.clientWidth;
            this.y = 0;
            this.w = 20;
            this.h = 60;
            c.beginPath();
            c.rect(this.x, this.y, this.w, this.h)
            c.fill();
          }
        }
    }

    var holder = new Squares();

    var xOffset = 20;
    setInterval(function() {
      c.clearRect(0,0,tryCanvas.clientWidth, tryCanvas.clientHeight);
      holder.draw(xOffset)
      xOffset--;
    }, 1000)


 </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM