Creating an HTML5 page using canvas and javascript to draw a set number of music
ID: 646718 • Letter: C
Question
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.
Explanation / Answer
You need to change the x, might help to visualize on a piece of paper or paint with grids what your doing.
This will make lines from top to the bottom
<!DOCTYPE HTML>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<span id=dbg
></span>
<br>
<canvas id=sheetmusic width="800" height="625"></canvas>
<br>
<div id=dbgD></div>
<script language="Javascript">
dbr = document.getElementById('dbgD');
function dbg(s){
dbr.innerHTML = dbr.innerHTML + "<br>" + s
}
window.onload = function(){
var canvas = document.getElementById('sheetmusic');
c = canvas.getContext('2d');
dbg(" canvas " + canvas + "; 2d " + c);
//c.fillStyle = 'white';
//c.fillRect(0,0, canvas.width, canvas.height);
canvas.width = canvas.width //clears
c.fillStyle = 'green';
heightDiff = 15;
numberLines = canvas.height / heightDiff
// Draw staves
for (var i=0; i< numberLines; i++){
c.strokeStyle = 'black';
c.beginPath();
c.moveTo(0,10 + (i * heightDiff));
c.lineTo(canvas.width, 10 + (i * heightDiff));
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, not sure what you want to do here
c.fillStyle = 'white';
//c.fillRect(0,52, canvas.width, 50);
}
};
</script>
Maybe a few tutorials on loops and using their vars will help ? http://www.echoecho.com/javascript9.htm not sure exactly what you want to achieve except make some lines that look like music notes?
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.