Search code examples
javascripthtmlcanvasmarkup

Reducing JavaScript Markup when drawing objects in HTML5


I'm trying to draw a few circles that will all have the same properties, but a different endingAngle, I don't want to write the entire circle code 5 times, is there a way to either assign most of the code to a class, and just change one variable for 5 different ID's?

Here are two of the 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 and .9*Math.PI are the only things that are going to change between circles, any way I can write the above so I don't have to write all of it 5 times?


Solution

  • You don't have to change your markup, you can do this :

    ['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 to duplicate the code or to call a function, you just have to add elements in the array.

    If you can't infer the angle from the index, then,

    • either you want to "hardcode" the data, then use a function (see other answer)
    • or you want to manage the data as data.

    In the latter case, you can do something like this :

     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();
    });