2011-12-16 72 views
2

我有以下的HTML ...HTML5画布 - 画出同样的事情在所有画布元素通过

<body onload="draw();"> 

    <p><a href=""><canvas class="demo2" width="6" height="12">Fallback</canvas> Back to (1)...</a></p> 
    <p><a href=""><canvas class="demo2" width="6" height="12">Fallback</canvas> Back to (2)...</a></p> 

</body> 

...和javascript:

function draw() {   
    var canvas2 = $('.demo2').get(0); // This draws in the first canvas 
    //var canvas2 = $('.demo2').get(); This doesn't draw at all 
    if (canvas2.getContext) { 
     var ctx2 = canvas2.getContext('2d'); 

     ctx2.beginPath(); 
     ctx2.moveTo(6,0); 
     ctx2.lineTo(6,12); 
     ctx2.lineTo(0,6); 
     ctx2.fillStyle = 'rgb(0,100,220)'; 
     ctx2.fill(); 
    } 
} 

我想什么发生的情况是所有类别为demo2的画布都被绘制。

我以为$('.demo2').get()会得到该类名称的所有元素。 $('.demo2').get(0)画在第一个,但我想画他们所有。

演示在http://jsfiddle.net/kMN3s/

回答

4

您可以使用.each来执行的东西每个.demo2http://jsfiddle.net/kMN3s/2/

function draw() {   
    $('.demo2').each(function() { 
     if (this.getContext) { // `this` is an element each time 
      var ctx2 = this.getContext('2d'); 

      ctx2.beginPath(); 
      ctx2.moveTo(6,0); 
      ctx2.lineTo(6,12); 
      ctx2.lineTo(0,6); 
      ctx2.fillStyle = 'rgb(0,100,220)'; 
      ctx2.fill(); 
     } 
    }); 
} 
+0

辉煌,谢谢。 – 2011-12-16 10:30:37

1

更新您的演示http://jsfiddle.net/kMN3s/1/

$('canvas.demo2').each(function() { } 
+0

+1很好,谢谢。 @pimvdb在你之前到达那里,所以我给他'接受'。 – 2011-12-16 10:30:27