canvas in HTML5 and creating multiple circles -
following w3c school explanation of canvas, understand creating shapes...
<script> var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d'); var centerx = canvas.width / 2; var centery = canvas.height / 2; var radius = 20; context.beginpath(); context.arc(centerx, centery, radius, 0, 2 * math.pi, false); context.fillstyle = 'green'; context.fill(); context.linewidth = 5; context.strokestyle = '#003300'; context.stroke(); </script>
this make green circle canvas is.
<canvas id="mycanvas"></canvas>
however - want apply "circle" multiple places on page, , doing id ridiculous.
how 1 apply context (as defined above) multiple canvas'?? i' assume using class, seems logical way.
<canvas class="reddot"></canvas> <canvas class="reddot"></canvas> <canvas class="reddot"></canvas> <canvas class="greendot"></canvas> <canvas class="greendot"></canvas> <canvas class="bluedot"></canvas> <canvas class="bluedot"></canvas> <canvas class="bluedot"></canvas>
you have iterate through each element apply changes. i.e:
var dots = document.getelementsbyclassname('dots'); (var i=0;i<dots.length;i++){ var canvas = dots[i]; var context = canvas.getcontext('2d'); // draw circles here }
ideally, have 1 canvas element can draw multiple circles
var canvas = document.getelementbyid('myoneandonlycanvas'); // using css , layering can make background var context = canvas.getcontext('2d'); dot('red',50,50); dot('blue',100,50); //etc.. function dot(color,x,y){ context.beginpath(); context.arc(y, y, radius, 0, 2 * math.pi, false); context.fillstyle = color; context.fill(); context.linewidth = 5; context.strokestyle = '#003300'; context.stroke(); }
but if doesn't fit use case using svg object?
since mentioned w3 schools: http://www.w3schools.com/svg/ ideally check out: http://www.w3.org/graphics/svg/
mind, dom heavy pages can hurt load times. depending on want might wiser use image (eg. large cluster of dots).
Comments
Post a Comment