2017-08-17 88 views
0

我试图表现出同样高度的画布多个管道,但它呈现出单管,而不是它的很多,甚至使用一个循环后如何让多个元素在画布

<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> 

如果我在数组中推入构造函数,它不会在画布中显示任何内容,并且在控制台中显示未定义或NaN。 但是,如果我没有这个“它”它产生rects的数量。 我在这里做错了什么?

+0

'c.clearRect(0,0,tryCanvas.clientWidth,tryCanvas.clientHeight);'做什么? – Teemu

+0

它基本上清除画布 – tankit88

+0

不仅基本上,它几乎清除... – Teemu

回答

2

更新沿着屏幕

移动酒吧见该工作示例: https://codepen.io/bkfarns/pen/braWQB?editors=1010

This.draw只能获得价值从for循环的最后一次迭代产生。

也作为一个侧面节点,通常而不是new Squares您可以调用构造函数,如new Squares()。当你调用构造函数时,你正在调用一个方法。

但我认为下面的代码可以解决您的问题。试试看:

<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> 
+0

'new Squares'和'new Squares()'有什么区别? – guest271314

+0

我刚刚在控制台中试了一下,显然它做了同样的事情。 但是通常我们总是有parens在必要时传递参数,就像一个普通的方法。 请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new – user3692823

+0

非常感谢您的帮助,这让我能够做到这一点..但是当我添加更新功能使管道沿x轴移动,该部分不工作。 'this.update = function(){ this.x - = 1; this.draw(); } var holder = new Squares(); setInterval(callFun,10); function callFun(){ holder.update(); } 这部分不起作用。 – tankit88