p5.js loadFont function? - javascript

How can I change the font in p5.js? It does not recognize the Processing term "loadFont," does not carry over a font from CSS, nor does it let me put in a .vlw file or link to a GoogleFont. At least, not in any way I have tried.
The references page only contains "text" and "textFont" options (in the Typography section at the end of the p5.js references page), neither of which allow for actually specifying a font.
I have also tried the
text.style('font-family', 'Walter Turncoat');
option listed here (https://github.com/lmccart/p5.js/wiki/Beyond-the-canvas) to no avail. It actually broke the whole page. In CSS:
#font-face {
font-family: 'Walter Turncoat';
src: url('http://fonts.googleapis.com/css?family=Walter+Turncoat');
}
Processing version did not work:
var type = loadFont("AmericanTypewriter-48.vlw");
var smallType = loadFont("AmericanTypewriter-14.vlw");
Also,
var type = "Helvetica";
which they have in the examples for text and textFont does not work.
There has to be a way to have another font. Please help!

The examples given in the reference work fine. Run code snippet below for results. What do you mean when you say it doesn't work for you?
function setup() {
createCanvas(640, 480);
}
function draw() {
fill(0);
textSize(36);
textFont("Georgia");
text("Hello World! in Georgia.", 12, 40);
textFont("Arial");
text("Hello World! in Arial.", 12, 100);
textFont("Walter Turncoat");
text("Hello World! in Walter Turncoat.", 12, 160);
}
<link href="http://fonts.googleapis.com/css?family=Walter+Turncoat&.css" rel="stylesheet"/>
<script src="http://cdn.jsdelivr.net/p5.js/0.3.8/p5.min.js"></script>

To load a font in p5.js you need a .ttf or .otf file, p5 doesn't work with .vlw files. So to use a font in p5 you need to:
Get a .ttf or .otf font file. This font file will be loaded on execution time to your app.
Declare a global variable to keep the font.
Load the font with loadFont in a preload function.
After the font is loaded you must use textFont() to tell p5 that this is the font to be used.
Print someting with text().
Here is an example:
var myFont, fontReady = false;
function fontRead(){
fontReady = true;
}
function preload() {
myFont = loadFont("./fonts/MyfontFile.ttf", fontRead);
}
function setup() {
createCanvas(720, 400);
doyourSetup();
}
function draw() {
background(255);
if (fontReady) {
textFont(myFont);
text("Hello World!", 10, 30);
}
}

You need to load the font in preload:
var font;
function preload() {
font = loadFont('thefont.ttf');
}
function setup() {
createCanvas(600, 400);
textFont(font);
}
function draw() {
background(255);
text('The Text', 280, 300);
}

According to the docs, if you have a font file that p5 recognizes (such as otf, ttf ect...), you can load that font file and than use it with the following 2 lines of code:
var myFont = loadFont('customfont.ttf');
textFont(myFont);
and then write with the font like this:
text('Stack overflow', 2,2);

var myfont;
function preload() {
font = loadFont('font.ttf)
}
function setup{
createCanvas(400, 400)
}
function draw{
textFont(myfont)
text("Hello", 200, 200)
}
There is no need for a ready function because newer versions of
p5.js will not display the project until it is finshed loading if it is in the preload function.

Related

ReferenceError: loadAnimation is not defined at /sketch.js:6:3

var boat,groundImage; //variables declared
function preload(){
boat = loadAnimation("b2.png"); //loading animation
groundImage = loadImage("b1.jpg");
}
function setup() {
createCanvas(600, 400); //draw canvas
}
function draw()
{
background(180);
image(groundImage,0,0);
animation(boat,0,0); //locate animation
}
here is a simple code for using animation in p5.js editor. But I got an error as: ReferenceError: loadAnimation is not defined at /sketch.js:6:3
The loadAnimation() function is not part of p5.js. It is added by the p5.play add-on. I can only assume that you have forgotten to add a reference to p5.play in your index.html because you did not include a minimal, reproducible example.
<script src="https://molleindustria.github.io/p5.play/lib/p5.play.js"></script>

Can't get a canvas to display a custom font

Canvas.filltext won't render custom font (though body text will, and canvas.filltext will render local fonts)
I want to paint some text on a canvas, using a custom font called jelleebold. Here's an abbreviated version of the function that I hoped would do that:
function paintLinkNameOnCanvas(linkName, canvas){
let context = canvas.getContext('2d');
context.font = "25px jelleebold";
context.fillText(linkName, 50, 50);
return canvas;
}
However, the font that gets used is whatever the browser (Chrome) uses as its fallback (Times New Roman, I think). Here's the html link
<link href="./CSS/stylesheet.css" rel="stylesheet" type="text/css">
and the css, downloaded from fontsquirrel, and modified to suit my local directory structure:
#font-face {
font-family: jelleebold;
src: url('/fonts/jellee-roman-webfont.woff2') format('woff2'),
url('/fonts/jellee-roman-webfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
I believe that this has worked, and Jelleebold has loaded successfully, because index.php contains:
<body style ="font-size: 50px; font-family: 'jelleebold'">
<div id= "output" >
test
</div>
etc.
and the word 'test' gets printed in jelleebold.
In contrast, if the paintLinkNameOnCanvas function specifies a font that is installed on the local machine (such as context.font = "25px 'Balford Base'"), the linkname does get painted in that font.
So why isn't the custom font being used to paint the linkname on the canvas?
And after a very helpful suggestion from Renato Bibiano, I've now produced an updated version of the function (shown below). The commented lines are a hint about the next problem; how do I get it to work with both woff- and woff2-formatted fonts? It works with either one, but not the other.
function paintLinkNameOnCanvas(linkName, canvas){
let earl = "";
// earl += "url('/fonts/jellee-roman-webfont.woff' ) format('woff' ";
// earl += ", ";
earl += "url('/fonts/jellee-roman-webfont.woff2')format('woff2')";
let f = new FontFace("jelleebold", earl);
f.load().then(function() {
let context = canvas.getContext('2d');
context.font = '23px jelleebold';
context.fillText('Hey, world', 0, 100);
});
return canvas;
}
I feel that taking the comment slashes out should produce something sensible, but if both specifications (woff and woff2) are included, the ouput reverts to the default font, TNR.

The font, "riffic free-bold" doesn't work in p5.js

So I'm doing the obvious...
var font;
function preload() {
font = loadFont('assets/text/riffic.ttf');
}
function setup() {
createCanvas(600, 600);
}
and then to call it I use...
function draw() {
textFont(font);
text("Hello", 100, 100);
}
When I try to use this font, the console tells me this...
Uncaught TypeError: Cannot read property 'length' of undefined
at Substitution.getDefaultScriptName (p5.js:31993)
at Font.stringToGlyphs (p5.js:27954)
at Font.forEachGlyph (p5.js:28069)
at Font.getAdvanceWidth (p5.js:28144)
at p5.Font._textWidth (p5.js:63498)
at p5.Font._handleAlignment (p5.js:63523)
at p5.Font._getPath (p5.js:63339)
at p5.Font._renderPath (p5.js:63458)
at p5.Renderer2D._renderText (p5.js:48828)
at p5.Renderer2D.text (p5.js:48788)
but no matter where I get it from the font style "Riffic free-bold just will not work with p5.js for me! Is there some kind of reason for this? Is riffic free-bold different from other fonts? If so, how? (I REQUIRE riffic free-bold, so I can't just use another font.)

Can I change javascript draw function to an image?

I found a gamecode on github [https://github.com/maryrosecook/retro-games] today. I want to edit it and use png images instead of the draw function, is there anyway I can do it?
Thank you.
BodyBlock.prototype = {
draw: function(screen) {
drawRect(screen, this, "black");
}
drawRect() was custom, from scratch function.
var drawRect = function(screen, body, color) {
screen.fillStyle = color;
screen.fillRect();
};
What you are looking for is standard javascript canvas Method.
http://www.w3schools.com/tags/canvas_fillrect.asp
Tutorial : http://www.html5canvastutorials.com/tutorials/html5-canvas-lines/

How to know if a font (#font-face) has already been loaded?

I'm using Font-Awesome, but while the font files are not loaded, the icons appear with .
So, I want these icons to have display:none while files are not loaded.
#font-face {
font-family: "FontAwesome";
src: url('../font/fontawesome-webfont.eot');
src: url('../font/fontawesome-webfont.eot?#iefix') format('eot'), url('../font/fontawesome-webfont.woff') format('woff'), url('../font/fontawesome-webfont.ttf') format('truetype'), url('../font/fontawesome-webfont.svg#FontAwesome') format('svg');
font-weight: normal;
font-style: normal;
}
How do I know that these files have been loaded and I'm finally able to show the icons?
Edit:
I'm not talking when the page is loaded (onload), because the font could be loaded before the whole page.
Now on GitHub: https://github.com/patrickmarabeas/jQuery-FontSpy.js
Essentially the method works by comparing the width of a string in two different fonts. We are using Comic Sans as the font to test against, because it is the most different of the web safe fonts and hopefully different enough to any custom font you will be using. Additionally we are using a very large font-size so even small differences will be apparent. When the width of the Comic Sans string has been calculated, the font-family is changed to your custom font, with a fallback to Comic Sans. When checked, if the string element width is the same, the fallback font of Comic Sans is still in use. If not, your font should be operational.
I rewrote the method of font load detection into a jQuery plugin designed to give the developer the ability to style elements based upon whether the font has been loaded or not. A fail safe timer has been added so the user isn’t left without content if the custom font fails to load. That’s just bad usability.
I have also added greater control over what happens during font loading and on fail with the inclusion of classes addition and removal. You can now do whatever you like to the font. I would only recommend modifying the fonts size, line spacing, etc to get your fall back font as close to the custom as possible so your layout stays intact, and users get an expected experience.
Here's a demo: http://patrickmarabeas.github.io/jQuery-FontSpy.js
Throw the following into a .js file and reference it.
(function($) {
$.fontSpy = function( element, conf ) {
var $element = $(element);
var defaults = {
font: $element.css("font-family"),
onLoad: '',
onFail: '',
testFont: 'Comic Sans MS',
testString: 'QW#HhsXJ',
delay: 50,
timeOut: 2500
};
var config = $.extend( defaults, conf );
var tester = document.createElement('span');
tester.style.position = 'absolute';
tester.style.top = '-9999px';
tester.style.left = '-9999px';
tester.style.visibility = 'hidden';
tester.style.fontFamily = config.testFont;
tester.style.fontSize = '250px';
tester.innerHTML = config.testString;
document.body.appendChild(tester);
var fallbackFontWidth = tester.offsetWidth;
tester.style.fontFamily = config.font + ',' + config.testFont;
function checkFont() {
var loadedFontWidth = tester.offsetWidth;
if (fallbackFontWidth === loadedFontWidth){
if(config.timeOut < 0) {
$element.removeClass(config.onLoad);
$element.addClass(config.onFail);
console.log('failure');
}
else {
$element.addClass(config.onLoad);
setTimeout(checkFont, config.delay);
config.timeOut = config.timeOut - config.delay;
}
}
else {
$element.removeClass(config.onLoad);
}
}
checkFont();
};
$.fn.fontSpy = function(config) {
return this.each(function() {
if (undefined == $(this).data('fontSpy')) {
var plugin = new $.fontSpy(this, config);
$(this).data('fontSpy', plugin);
}
});
};
})(jQuery);
Apply it to your project
.bannerTextChecked {
font-family: "Lobster";
/* don't specify fallback font here, do this in onFail class */
}
$(document).ready(function() {
$('.bannerTextChecked').fontSpy({
onLoad: 'hideMe',
onFail: 'fontFail anotherClass'
});
});
Remove that FOUC!
.hideMe {
visibility: hidden !important;
}
.fontFail {
visibility: visible !important;
/* fall back font */
/* necessary styling so fallback font doesn't break your layout */
}
EDIT: FontAwesome compatibility removed as it didn't work properly and ran into issues with different versions. A hacky fix can be found here: https://github.com/patrickmarabeas/jQuery-FontFaceSpy.js/issues/1
Try WebFont Loader (github repo), developed by Google and Typekit.
This example first displays the text in the default serif font; then after the fonts have loaded it displays the text in the specified font. (This code reproduces Firefox's default behavior in all other modern browsers.)
Actually, there is a good way to understand all fonts begin to download or loaded completely or not and fall into some errors, but it is not just for a specific font, pay attention to the following code:
document.fonts.onloading = () => {
// do someting when fonts begin to download
};
document.fonts.onloadingdone = () => {
// do someting when fonts are loaded completely
};
document.fonts.onloading = () => {
// do someting when fonts fall into some error
};
And also there is an option that returns Promise and it could handle with .then function:
document.fonts.ready
.then(() => console.log('do someting at the final with each status'))
Here is a different approach to the solutions from others.
I'm using FontAwesome 4.1.0 to build WebGL textures. That gave me the idea to use a tiny canvas to render a fa-square to, then check a pixel in that canvas to test whether it has loaded:
function waitForFontAwesome( callback ) {
var retries = 5;
var checkReady = function() {
var canvas, context;
retries -= 1;
canvas = document.createElement('canvas');
canvas.width = 20;
canvas.height = 20;
context = canvas.getContext('2d');
context.fillStyle = 'rgba(0,0,0,1.0)';
context.fillRect( 0, 0, 20, 20 );
context.font = '16pt FontAwesome';
context.textAlign = 'center';
context.fillStyle = 'rgba(255,255,255,1.0)';
context.fillText( '\uf0c8', 10, 18 );
var data = context.getImageData( 2, 10, 1, 1 ).data;
if ( data[0] !== 255 && data[1] !== 255 && data[2] !== 255 ) {
console.log( "FontAwesome is not yet available, retrying ..." );
if ( retries > 0 ) {
setTimeout( checkReady, 200 );
}
} else {
console.log( "FontAwesome is loaded" );
if ( typeof callback === 'function' ) {
callback();
}
}
}
checkReady();
};
As it uses a canvas it requires a fairly modern browser, but it might work on IE8 as well with the polyfill.
Here's another way of knowing if a #font-face has already been loaded without having to use timers at all: utilize a "scroll" event to receive an instantaneous event when the size of a carefully crafted element is changed.
I wrote a blog post about how it's done and have published the library on Github.
Try something like
$(window).bind("load", function() {
$('#text').addClass('shown');
});
and then do
#text {visibility: hidden;}
#text.shown {visibility: visible;}
The load event should fire after the fonts are loaded.
alternatively, you could add font-display: block to your #font-face declaration.
this instructs browsers to render the fallback font as invisible until your font is loaded, no need for display: none or any javascript load font detection
Solution for Typescript, Angular.
If you are working with Angular, you can use this module in order to do a font check.
// document.fonts.check extension
import type {} from 'css-font-loading-module';
ngOnInit() {
this.onFontLoad();
}
public onFontLoad() {
let myTimer = setInterval(() => {
if (document.fonts.check('14px MyFont')) {
console.log('Font is loaded!');
clearInterval(myTimer);
} else {
console.log('Font is loading');
}
}, 1);
}
Also, some fonts are extremely heavy. Therefore, you can add a loading screen while the font is loading and remove the loading screen when the font is loaded. I believe this is a better approach rather than changing your CSS class to display: none, merely because it might take 3-4+ seconds to download some fonts if the user has slow internet.
This is an alternate approach that will at least ensure that font-awesome is loaded, NOT a complete solution to the OP. Original code found in the wordpress forums here https://wordpress.stackexchange.com/a/165358/40636.
It's agnostic and will work with any font style resource like font-awesome where a font-family can be checked. With a little more thought I bet this could be applied to much more...
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script>
(function($){
var faSpan = $('<span class="fa" style="display:none"></span>').appendTo('body');
if (faSpan .css('fontFamily') !== 'FontAwesome' ) {
// Fallback Link
$('head').append('<link href="/css/font-awesome.min.css" rel="stylesheet">');
}
faSpan.remove();
})(jQuery);
</script>
Use the below code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="canvasFont" width="40px" height="40px" style="position: absolute; display: none;"></canvas>
<script>
function IsLoadedFonts()
{
var Args = arguments;
var obj = document.getElementById('canvasFont');
var ctx = obj.getContext("2d");
var baseFont = (/chrome/i.test(navigator.userAgent))?'tims new roman':'arial';
//................
function getImg(fon)
{
ctx.clearRect(0, 0, (obj).width, (obj).height);
ctx.fillStyle = 'rgba(0,0,0,1.0)';
ctx.fillRect( 0, 0, 40, 40 );
ctx.font = '20px '+ fon;
ctx.textBaseline = "top";
ctx.fillStyle = 'rgba(255,255,255,1.0)';
ctx.fillText( '\u0630', 18, 5 );
return ctx.getImageData( 0, 0, 40, 40 );
};
//..............
for(var i1=0; i1<Args.length; i1++)
{
data1 = getImg(Args[i1]);
data2 = getImg(baseFont);
var isLoaded = false;
//...........
for (var i=0; i<data1.data.length; i++)
{
if(data1.data[i] != data2.data[i])
{isLoaded = true; break;}
}
//..........
if(!isLoaded)
return false;
}
return true;
};
setTimeout(function(){alert(IsLoadedFonts('myfont'));},100);
</script>
</body>
Can check many fonts:
setTimeout(function(){alert(IsLoadedFonts('font1','font2','font3'));},100);
The below code works in opera only but is easy:
if(!document.defaultView.getComputedStyle(document.getElementById('mydiv'))['fontFamily'].match(/myfont/i))
alert("font do not loaded ");

Categories

Resources