search

Home  >  Q&A  >  body text

html5 - 请问利用font-face定义的字体怎么在canvas里应用?

请问利用font-face定义的字体怎么在canvas里应用?

巴扎黑巴扎黑2786 days ago961

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-17 14:55:55

    <style>
        @font-face {
          font-family: "_________";  //下划线填字体名称
          src: url("_________");  //下划线填字体文件
        }
    </style>
    
    <script type="text/javascript">
        function draw() {    
            var ctx = document.getElementById('canvas').getContext('2d');    
            var img = new Image();    
            img.onload = function(){         
              ctx.drawImage(img,0,0);    
              ctx.beginPath();    
              ctx.fillStyle    = '#000';
              ctx.font         = "60px Automania";
              ctx.textBaseline = 'top';
              ctx.fillText('what this font looks', 0, 5);
              ctx.stroke();
            }
            img.src = 'img.png';      
          }
    </script>
    
    <input onclick="draw()" type="button" value="test" />
    <canvas id="canvas" width="800" height="800"></canvas>
    

    However, it is not recommended to use custom fonts in canvas because the font file loads too slowly. .

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 14:55:55

    1. You must wait until the font is downloaded before rendering the canvas so that the font can be effective
    2. The font referenced in the canvas must have a tag (span, p, etc.) in the document stream to reference the font!! !This is the biggest pitfall!!!

    reply
    0
  • Cancelreply