2011-12-16 12 views
2

により、すべてのcanvas要素にHTML5キャンバス - ...私は、次のHTMLを持っているクラス

<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/2/:あなたは、各.demo2のために物事を実行するために.eachを使用することができますhttp://jsfiddle.net/kMN3s/

答えて

4

デモ。

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

ブリリアント、感謝を更新しました。 –

1

あなたのデモhttp://jsfiddle.net/kMN3s/1/

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

+1ありがとう、ありがとう。 @pimvdbはあなたの直前にそこに着いたので、私は彼に「受け入れられる」と言います。 –

関連する問題