在下面的代码中,我通过传递一个字符串来更改 HTML5 画布字体。然后在第二种情况下,我使用数组和变量。第一个案例有效。第二种情况不会改变字体。问题可能出在我构造变量的方式上。
<!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>