Javascript Canvas – How to Create Repetitive Drawings

canvashtml5javascriptloops

Creating an HTML5 page using canvas and javascript to draw a set number of musical staves on the page, spaced a pre-determined amount in between.

What I have is re-drawn on top of the canvas 10 times, and what I really need is something that's spaced out apart every time the loop is drawn.

I tried to create a JSFiddle, but it doesn't draw anything (which I'm sure is user-error), so here's the js file:

window.onload = function(){

var canvas = document.getElementById('sheetmusic');
    c = canvas.getContext('2d');

c.fillStyle = 'white';
c.fillRect(0,0, canvas.width, canvas.height);

//  Draw staves
for (var i=0; i<10; i++){
    c.strokeStyle = 'black';
    c.beginPath();
    c.moveTo(0,10);
    c.lineTo(canvas.width,10);
    c.stroke();
    c.moveTo(0,20);
    c.lineTo(canvas.width,20);
    c.stroke();
    c.moveTo(0,30);
    c.lineTo(canvas.width,30);
    c.stroke();
    c.moveTo(0,40);
    c.lineTo(canvas.width,40);
    c.stroke();
    c.moveTo(0,50);
    c.lineTo(canvas.width,50);
    c.stroke();
    // staff whitespace
    c.fillStyle = 'white';
    c.fillRect(0,52, canvas.width, 50);
    }
};

I'm just not certain how to append i from my loop into the height attribute of my stroke.

Best Answer

Figured out what I was going for. Wanted to use loops to make the code as concise as possible, but ran into a few problems until I achieved this.

window.onload = draw;

function draw() {
    var canvas = document.getElementById('sheetmusic');
    var c = canvas.getContext('2d');
    var whitespace = 0;
    var ycoordinate = 10;

    //draw the staves 'x' number of times requested
    for (var x = 1; x <= 10; x++) {

        // draw the staff
        for (var i = 1; i <= 5; i++){
            c.strokeStyle = 'black';
            c.moveTo(0,ycoordinate);
            c.lineTo(canvas.width,ycoordinate);
            c.stroke();
            ycoordinate = ycoordinate + 10;
        }

        //draw white space beneath each staff
        c.fillStyle = 'white';
        c.fillRect(0,whitespace + 52,canvas.width,52);
        whitespace = whitespace + 100;
        ycoordinate = ycoordinate + 30;

    }
}

Now I can set x to repeat as many times as I want, in order to draw music staves in javascript, with the correct amount of adjustable whitespace in between them.

Had to go back and look up some more information on loops, as suggested by tgkprog. Thanks!

Demo'able JS Fiddle at http://jsfiddle.net/ShawnCodes/K8j7u/1/

Related Topic