Reducing JavaScript Markup when drawing objects in HTML5 -


i'm trying draw few circles have same properties, different endingangle, don't want write entire circle code 5 times, there way either assign of code class, , change 1 variable 5 different id's?

here 2 of circles

var canvas = document.getelementbyid('firefox'); var context = canvas.getcontext('2d'); context.beginpath(); context.arc(64, 64, 60, 1.5*math.pi, .3*math.pi, true); context.linewidth = 8; context.linecap = "round"; context.strokestyle = '#c5731e'; context.stroke();  var canvas = document.getelementbyid('chrome'); var context = canvas.getcontext('2d'); context.beginpath(); context.arc(64, 64, 60, 1.5*math.pi, .9*math.pi, true); context.linewidth = 8; context.linecap = "round"; context.strokestyle = '#c5731e'; context.stroke(); 

.3*math.pi , .9*math.pi things going change between circles, way can write above don't have write of 5 times?

you don't have change markup, can :

['firefox','chrome'].foreach(function(id, index){     var canvas = document.getelementbyid(id);     var context = canvas.getcontext('2d');     context.beginpath();     context.arc(64, 64, 60, 1.5*math.pi, (index+1)*0.3*math.pi, true);     context.linewidth = 8;     context.linecap = "round";     context.strokestyle = '#c5731e';     context.stroke(); }); 

you don't have duplicate code or call function, have add elements in array.

if can't infer angle index, then,

  • either want "hardcode" data, use function (see other answer)
  • or want manage data data.

in latter case, can :

 var data = [    {id:'firefox', angle:33},    {id:'chrome', angle:43}  ];  data.foreach(function(e){     var canvas = document.getelementbyid(e.id);     var context = canvas.getcontext('2d');     context.beginpath();     context.arc(64, 64, 60, 1.5*math.pi, e.angle, true);     context.linewidth = 8;     context.linecap = "round";     context.strokestyle = '#c5731e';     context.stroke(); }); 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -