text() throws an error - when font loaded outside of preload()

Hi all. Can't figure this one out. I'm setting an interval to wait for fonts to load before using them. However, text() is throwing an error - unless the font is loaded in preload(). Any idea why the error?

Simple example here: http://dfilm.com/lucs/test_font/fontest.html

If you move the loadFont() statements up to preload(), it works fine. I don't want to load the fonts in preload so that the page loads as quickly as possible.

Answers

  • edited January 2016
    • Callbacks very hardly return anything.
    • You need to flag that something happened in some variable instead.
    • Then within draw(), always check whether the resource was successfully loaded before using it.
    • We check such via the "flag" variable set as true inside the callback.
  • Sorry, I'm not following. Are you saying that the loadFont() callback is called before the font is actually loaded?

    Is there another way to check if the resource is loaded, other than by using its callback?

  • Untested: treat as pseudocode

    var isLoaded;
    
    function setup() {
        loadFont("myFont", 
            // callback:
            function() {
             isLoaded = true;
        });
    }
    
    function draw() {
        if(isLoaded) {
            // do stuff with font...
        }
    }
    
  • edited January 2016

    Hey, I tried your code above and discovered something very interesting. It errors out when preload() is defined - but works fine if preload() is removed. This a bug?

    //----------------DOES NOT WORK----------------
    var isLoaded;
    var myfonthandle;
    function preload() {
     //do nothing
    }
    function setup() {
      var mycanvas = createCanvas(200, 200);
      myfonthandle = loadFont('assets/fonts/proxima-nova-bold.ttf', assetloaded); 
    }
    function draw() {
      if (isLoaded){
        textFont(myfonthandle);
        text("test", 100,100);
      }
    }
    function assetloaded(){
      isLoaded = true;
    }
    //----------------WORKS----------------
    var isLoaded;
    var myfonthandle;
    function setup() {
      var mycanvas = createCanvas(200, 200);
      myfonthandle = loadFont('assets/fonts/proxima-nova-bold.ttf', assetloaded); 
    }
    function draw() {
      if (isLoaded){
        textFont(myfonthandle);
        text("test", 100,100);
      }
    }
    function assetloaded(){
      isLoaded = true;
    }
    
Sign In or Register to comment.