I am creating a canvas to be used for the user writing on. The canvas script includes drawing guidelines and text naming the guidelines. It begins like this:
<script>
var canvas = document.getElementById('sketch');
// Always check for properties and methods to make sure your code doesn't break in other browsers.
if (canvas.getContext)
{
var context = canvas.getContext('2d');
// ascender height
context.fillStyle = '#cccccc'; // put color before '.font'
context.font = '20px sans-serif';
context.fillText('ascender height', 20, 40);
context.beginPath();
// Staring point
context.moveTo(0,45);
// End point
context.lineTo(500,45);
// Make the line visible
context.lineWidth = 1;
context.strokeStyle = '#ccc';
context.stroke();
. . .
</script>
This runs on for about 150 lines.
There is a button that clears the canvas, and it points to a function that is almost exactly the same as the above code. It begins like this:
<script>
function clearCanvas() {
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
// ascender height
context.fillStyle = '#cccccc';
context.font = '20px sans-serif';
context.fillText('ascender height', 20, 40);
context.beginPath();
context.moveTo(0,45);
context.lineTo(500,45);
context.lineWidth = 1;
context.strokeStyle = '#ccc';
context.stroke();
. . .
</script>
This also runs for about 150 lines, duplicating the above code.
How can I put the identical code in a function so it is called just once?
I tried replacing the top code with the following to call the clearCanvas() code, but the canvas stayed blank when the page loaded:
<script>
var canvas = document.getElementById('sketch');
//Always check for properties and methods, to make sure your code doesn't break in other browsers.
if (canvas.getContext)
{
var context = canvas.getContext('2d');
clearCanvas();
}
</script>
I expect to use this code online, and in iPhone and Android apps.