I am trying to draw the same thing on multiple canvases gotten by class selector. What am I doing wrong?
var canvases = document.getElementsByClassName('canvas');
for( var i=0; i<canvases.length; i++){
ctx = canvases[i].getContext('2d');
ctx.arc(50, 50, 50, 0, 1.5*Math.PI);
ctx.lineWidth = 15;
ctx.strokeStyle = 'black';
ctx.stroke();
}
Her's the fiddle
You need to declare them as <canvas> elements, not <div> elements. Canvases are their own specific HTML5 element.
Accordingly can also get rid of the class and use getElementsByTagName instead of getElementsByClassName with a few minor CSS and markup changes:
HTML
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
CSS
canvas {
width: 100px;
height: 100px;
background-color: yellow;
display: inline-block;
}
JS
var canvases = document.getElementsByTagName('canvas');
for( var i=0; i<canvases.length; i++){
ctx = canvases[i].getContext('2d');
ctx.arc(50, 50, 50, 0, 1.5*Math.PI);
ctx.lineWidth = 15;
ctx.strokeStyle = 'black';
ctx.stroke();
}
FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With