Monday, May 16, 2011

Google Web Fonts, SVGo and code sketching with goplay


SVGo and Google web fonts
This program, webfonts, demonstrates Google Web Fonts and its API with SVGo. The key to its operation is the URI:
http://fonts.googleapis.com/css?family={fonts}

where {fonts} is a pipe-delimited list of font names. The result of performing a HTTP GET on this URI is CSS code that specifies the fonts. For example,

http://fonts.googleapis.com/css?family=Pacifico 
produces:
@font-face {
font-family: 'Pacifico';
font-style: normal;
font-weight: normal;
src: local('Pacifico'), url('http://themes.googleusercontent.com/font?kit=fKnfV28XkldRW297cFLeqfesZW2xOQ-xsNqO47m55DA') format('truetype');
}

The program works by using a Go function to perform the GET (googlefont(fontname string)), and place the resulting CSS in a SVG defs element. The program is then able to use the web fonts by name just like any other local font. In this case looping over the names in the list, and displaying "Hello, World" in the corresponding font.

The screenshot shows the code and output in Google Chrome (although any modern browser that can handle inline SVG will work), using a web app that comes with the Go distribution, goplay. Goplay allows you to "play" with snippets of Go code and quickly compile and see the results in a web browser. In the case of programs like the one shown, the generated SVG is placed in-line, interpreted directly, showing the picture.

Here's how to run it: go to a directory where your code lives, and then run goplay -html, which sends the results unaltered to the browser, instead of in a plain text block. A word of caution from the goplay documentation: anyone with access to the goplay web interface can run arbitrary code on your computer. Goplay is not a sandbox, and has no other security mechanisms. Do not deploy it in untrusted environments.

cd [dir]
goplay -html
Next, point your browser to the content served by goplay (which listens on localhost, port 3999 by default):

http://localhost:3999/webfonts.go

Your code will be shown in the textarea, ready to be edited and built. Hit Shift-ENTER and code is compiled and run with the output next to the code. If you want to tweak the program, by changing say, a font name or the string to be displayed, just move to the textarea, make the change, and hit Shift-ENTER again. This method allows you to sketch in code, with immediate feedback.

With the WebKit Inspector found in Chrome and Safari, you can examine timing, code, and font information.


SVGo and Webfonts: network timing

SVGo and Webfonts: generated code

SVGo and Webfonts: font resource

1 comment:

Mike said...

Tx for sharing. Would You like to post as well, how to do the same on Google App Engine with Go? BR