Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript draw on multiple canvases

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

like image 611
Marián Zeke Šedaj Avatar asked Nov 22 '25 12:11

Marián Zeke Šedaj


1 Answers

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

like image 159
Ennui Avatar answered Nov 24 '25 00:11

Ennui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!