Canvas How to - Change font in loop








Question

We would like to know how to change font in loop.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from   w ww  .j  av a  2s .  c om-->
    var fontArray = new Array();    
    fontArray.push("Antiqua");            
    fontArray.push("Arial");  
    fontArray.push("Monospace");    
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.font  = "25pt Arial";   
    context.fillText('CSS', 30, 30);            
    context.font  = "25pt Monospace";   
    context.fillText('Canvas', 30, 80);            

    for(x=0;x<3;x++){
        var fontText = "20pt " + fontArray[x];           
        context.font = fontText;
        context.fillText('java2s.com', 120, 140+(x*50));             
    }
}
</script>
</head>
<body>
  <canvas id="myCanvas" width="800" height="600"></canvas>
</body>
</html>

The code above is rendered as follows: