2

In the following code, I change an HTML5 canvas font by passing a string. Then in the second case, I use an array and variables. The first case works. The second case does not change fonts. Problem is probably in the way I construct the variable.

<!DOCTYPE HTML>
<html>

<body>
    <canvas id="myCanvas" width="800" height="600"></canvas> 

<script>
// array of fonts
var fontArray = new Array();    
fontArray.push("Antiqua");            
fontArray.push("Arial");  
fontArray.push("Comic Sans");    

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

// This works
context.font  = "25pt Arial";   
context.fillText('This works ', 30, 30);            
context.font  = "25pt Monospace";   
context.fillText('This works ', 30, 80);            


// This works but shows no varaition of font
for(x=0;x<3;x++){
    var fontText = "\'" + "20pt " + fontArray[x] + "\'" ;           
    context.font  = fontText;
    console.log(fontText);   // print to console
    context.fillText('This works but shows no variation of font', 120, 140+(x*50));             
}
</script>
1
  • 1
    There's no need for the escaped single quotes. Commented May 15, 2013 at 2:22

2 Answers 2

1

What if you change:

var fontText = "\'" + "20pt " + fontArray[x] + "\'" ;

to

var fontText = "20pt " + fontArray[x];

Sign up to request clarification or add additional context in comments.

Comments

0

You shouldn't wrap the font string in single quotes. Remote that and it should work.

var fontText = "20pt " + fontArray[x];           

jsFiddle.

Another reason is that the fonts probably are not available on the client.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.