Check out my
new book!
HTML5 Games book
From Mario Kart to map navigation Ernest Delgado has turned my Mario Kart demo into a map navigation tool. Neat! This just popped up in my referrer logs and caught my eye. Ernest Delgado has taken apart the code from my Mario Kart project and turned it into a cool map navigation demo that dynamically downloads map tiles from http://openstreetmap.org/. Pretty cool, check it out here, even if he keeps calling me Joshua ok, he fixed the name :cool: Read more...
The FlickrBrot - Happy Birthday, Mandelbrot! Today is the birthday of Benoit Mandelbrot. About 30 years ago he pulled a bit of mathematical beauty out of his head that would make him father of what is called fractal geometry. Today, at 84, he's a retired Sterling Professor from Yale but is still getting awards thrown his way and even planets named after him. I thought I'd make something to mark his birthday since I've been playing a bit with fractals and JavaScript lately and because he's just damn cool. If you haven't already, check out the minimized sub-128 bytes Mandelbrot as well as the prettier and fancier Canvas fractal renderer to see the previous Mandelbrot related posts.

If you want to read more about the Mandelbrot set and fractals in general, I suggest you hit up Wikipedia (lots of juicy math!). What it comes down to, though, is that very simple formulas can produce the most fascinating, infinitely complex structures which in turn can be made into pretty pictures on a computer.

So, what I've spent my morning doing is hacking together my fractal renderer with some of the Flickr stuff I've also been doing. Instead of drawing colored pixels, it now pulls in a (limited) number of Flickr images and uses those to paint a visualization of the Mandelbrot set.

You can add a parameter to the url to search for a specific query at Flickr, ie. ".../flickrbrot/?puppies", although the images are painted so small it's pretty hard to discern what they really are. Searching for a specific color can sometimes produce a nicer looking result, ie. "?orange" or "?purple".

Only Firefox, Opera and Webkit nightly!

Check it out here.

Suggested listening: Jonathan Coulton - Mandelbrot Set

Read more...
Getting your ASCII on with Flickr
A while back I made a JavaScript image-to-ASCII-art converter using the image data access available through the Canvas element. For this Thursday's afternoon of fun and code, I decided to pull it back out of the closet and see what else I could do with it.
I'd already worked a bit with the Flickr API and found it quite a pleasant experience, so I decided to make a small application that pulls out Flickr photos and asciifies them for retro fun and profit.

How it works

You simply enter the search query of your choice and click the "Asciify" button. A request is then sent off to the Flickr server and any photos that match the query are returned. The image data is analyzed and turned into ASCII characters.

You can choose to have the characters colored the same color as the pixels they represent or simply leave them black/white. Optionally, you can have the background of the character colored as well by choosing "use blocks", making the final image more akin to a very blocky or pixelated version of the original, just made out of HTML rather than an actual image. Last, there's the option of having the background of the output be the average color of the original image. This may not look great for all images - and of course makes no sense if you're already using the blocks method.

Be aware that far from all Flickr images are suitable for Asciifying and some of the options just mentioned look better on some images than on others.

By default, the application will only ask for images that are licensed under the Creative Commons licenses to ensure that no feelings and/or intellectual property rights are hurt.

Since the application relies on the Canvas element and image data access, so far only Firefox, Opera and recent WebKit nightlies are supported.

Click here to start Asciifying Flickr

..or read on, if you're interested in

How it really works

The Flickr search part is pretty straight forward. A single request is sent, calling the "flickr.photos.search" method. We then get a list of photos from Flickr, but we can't access the data in these directly due to the same-origin policy of the Canvas element. To get around this, we're using a small proxy script (written in PHP) that does nothing other than retrieve the image file and pass it straight through to the browser.

The image is then painted (and downscaled since we're not using all pixels) on a hidden Canvas element, the image data is retrieved using getImageData() and each pixel in the image is analyzed. The brightness of the pixel is calculated using a simple RGB to brightness formula and this level of brightness is then mapped to a list of characters selected for their varying apparent brightness. The list used here is [ .,:;i1tfLCG08@] for black/white output and [ CGO08@] for colored output.

If the output is black/white, we just write the character to a string and move on to the next. If we're using colored output, we create a span element styled with the appropriate color. All these spans are the reason it can appear a bit more sluggish when using colors than when using black/white output. If the "blocks" option is on, we simply set the background of the character span to be the same color as the character itself. This way, the block appears solid but we can still drag the mouse over the output and select the ASCII text. For the last option, background color, the original image is downscaled to a 1x1 pixel Canvas and the color of this single pixel is read and used as the background color of the containing element.

Feel free to leave a comment or ask any questions.
Get Asciified!

Read more...
Embed Wikipedia summaries in articles A small, light-weight Wikipedia summary/preview widget that lets you include the first bit of a Wikipedia article in popups in your blog post, article, etc.

Links to Wikipedia are found everywhere in articles and blog posts, and I use them often myself when that extra level of information might be of interest to the reader but falls outside the scope of the actual article. However, sometimes a short blurb introducing the topic would be enough and would also keep the reader from disappearing into the time stealing rabbit hole that we all know Wikipedia can be.


Edit: The widget is now using the MediaWiki API rather than the AppJet gateway. Read update here.

One solution is to popup a small box with a summary from the Wikipedia article when the mouse moves over the word. There is one service that already provides something like this, the NBC owned Snap.com. Their SnapShot boxes display everything from website screenshots to Flickr images to Wikipedia summaries. That's cool, but I found it a bit too bulky just to display a few paragraphs of text and, as far I know, you don't get much in the way of customizing the appearance.

So I decided to create my own simple Wikipedia box. Fortunately most of Wikipedia is pretty neat and the first section usually contains a decent summary of what the article is about. So we can simply pull out all the text between the two first headings. Some articles have info boxes on the right that are ignored, as to only get pure text.

All this is done by a small AppJet JSON-P application that takes care of retrieving the article and locating the relevant portion of the text. The text is then processed a bit (ie. links are made to open in new windows and point to the absolute URL, reference ids are removed, etc) before it's all put in a nice little JSON package and returned to the client:

The 5000 most recently accessed articles are cached (there's a 50MB storage limit on each AppJet app and I'd rather err on the safe side.) making sure that delivery is speedy and that it doesn't hit Wikipedia's servers more than necessary.

The text is received by a bit of JavaScript which pops up a box containing the article summary and a small link to Wikipedia and the original article (and the GFDL license notice).

The box itself is rather simple, consisting of 4 simple elements. I know this is 2008 and there are no rounded corners or whatever the kids are using these days, but I wanted to keep it basic. The included style sheet should be self-explanatory and easy to change for your liking, although you might have to dive into the JS if you want something radically changed.

So, to use it, simply include the CSS and JS and start putting Wikipedia links in your text like this:

Example output (hover the mouse over the underlined words):

The sky above the port was the color of television, tuned to a dead channel.

"It's not like I'm using," Case heard someone say, as he shouldered his way through the crowd around the door of the Chat. "It's like my body's developed this massive drug deficiency." It was a Sprawl voice and a Sprawl joke. The Chatsubo was a bar for professional expatriates; you could drink there for a week and never hear two words in Japanese.
- Neuromancer by William Gibson


As you can see from this sample code, you simply make links to the relevant Wikipedia articles and the script should locate them automatically and enable the summary box.

Now, I'm not entirely sure whether or not this breaks the terms of use of Wikipedia. I do know they do not allow dynamically generated mirrors, but I'm not really sure in what category something like this would fall since the articles are dynamically downloaded (if not in cache) even if it isn't really a mirror as such. They used to have a crawl-delay of 1 page per second in their robots.txt, which is obeyed by the AppJet application. If you happen to get hit by that limitation (unlikely, I think) you'll be served a notice of that instead of the article text.

Another thing is that I'm not sure what kind of bandwidth quotas, if any, you might run into with AppJet. If every blog in the world started hitting the same AppJet application, I'm sure it would cause trouble, but that's unlikely to happen. Either way, it's very easy to simply clone the AppJet app if you want to use it on your own site and be safe.

I've tested the script in FF3, Opera 9.5, IE7, Safari 3.1 and Chrome and everything looks fine there.

Finally, download the files here: sumbox.js [4.8 KB] and sumbox.css [1.0 KB]
Read more...
A prettier, more styleable Digg button Lately, I've been looking at APIs at some of the big sites (like Flickr) and most recently I've been playing around with the Digg API. I've got something nice coming soon but as a simple intro project - and since I'm also working on a redesign of nihilogic.dk - I decided to pretty up the "Digg this" button as I've always found the official one rather ugly and inflexible.

Official Digg button
Even if including a dynamic "Digg this" button on your blog or website is easy as pie and only requires setting a few variables and including a JavaScript file from their server (which includes a few more files) it doesn't leave you a lot of options with regards to styling (ie. 2 different button sizes and a custom text color, that's about it). If you want it to blend better with your layout, you're stuck with a static link to Digg, trading appearance for interactivity.

A compromise

But, like any other respectable Web 2.0 service, Digg also has an API for developers wanting to use their services in their own software so I was surprised that I couldn't really find anyone who had built their own custom Digg buttons with this. The API is unfortunately somewhat limited (for security reasons, no doubt) in that it only allows you to retrieve info from Digg, ie. you cannot submit or vote for sites directly using the API. Still, this lets us at least get any information Digg has about the page in question so we can show something other than a dull "Digg This" link.

Let's skip to the end result for a bit. Doing this (the bare minimum):
Digg.createButton(document.getElementById("buttonParent"));
..will get you a Digg button that displays the number of Diggs the current page has gotten or, if it has not been submitted yet, the text "Submit". The first argument is required and is the DOM element the button will be added to. Clicking the button will take you to either the relevant page on Digg.com or to the submission page if it has not been submitted yet. The default button looks like this:


Options

Optionally, you can pass an options object like this:
Digg.createButton(
    document.getElementById("buttonParent"),
    {
        style : "digg_guy_dark",
        newWindow : true,
        autoUpdate : 30000
    }
);
This will give you a button in another style (more about those in a bit) which opens in a new window when clicked and automatically updates the displayed Digg count every 30 seconds.

A few more settings are available, the full list being:

  • url: Override the URL of the page. Useful for blog posts. Like "digg_url" for the official button.
  • title: Title to submit the page with (when not already submitted). Like "digg_title" for the official button.
  • description: Description to submit the page with (when not already submitted). Like "digg_bodytext" for the official button.
  • topic: Topic to submit the page under (when not already submitted). Like "digg_topic" for the official button.
  • media: Media to submit the page under (when not already submitted). Like "digg_media" for the official utton.
  • style: Style of the button. See below.
  • newWindow: If true, clicking the button will open a new window/tab.
  • autoUpdate: If true, the Digg count will be updated automatically.
  • updateInterval: Interval for the autoUpdate timer in miliseconds. Defaults to 30000, minimum is 10000.
  • onlyIfDugg: Only displays the button if the page has already been submitted to Digg.
  • submitText: Alternative text instead of "Submit", ie. "Digg This!" or whatever you fancy.

  • Styles

    Different styles are available and it's rather easy to create your own. See the included CSS files for examples. The CSS classes use a naming pattern like this:

    dg_container_<keyword>
    dg_diggs_link_<keyword>
    ...

    where keyword is the value of the "style" setting in the options object above.

    Ie. if you create your own style called "prettydigg", name your classes dg_container_prettydigg, dg_diggs_prettydigg, etc. and call Digg.createButton(parentNode, {style:"prettydigg"}).

    Below you'll see a selection of the styles in the package. There are only a couple and they're nothing fancy, but it's pretty easy to make your own.

    Default style
    Default style (red)
    Default style (dark)
    "Digg Guy" style (dark)
    "Badge" style (dark)

    There is one more method: Digg.setAPIKey(). Digg asks for an API key (that you decide) for each call, using the URL for your homepage or application is cool:
     Digg.setAPIKey("http://www.nihilogic.dk/");
    
    Anyway, that was a lot of words for a simple button.

    Get the files here: prettydigg-0.1.1.zip [15 KB]
    Read more...
    WolfenFlickr 3D - An unlikely mashup Long after B.J. Blazkowicz left Castle Wolfenstein guns blazing, the castle still holds a few secrets. On a super secret floor stolen art in the form of Flickr images has been found and for the first time, this strange gallery is now open to the public.

    If you're interested in building an engine such as this yourself, take a look at the Dev.Opera article I've written on this topic.

    This is a (silly) mashup of Wolfenstein 3D and Flickr. More specifically, it's a Javascript raycaster using Wolfenstein graphics that allows you to import Flickr images by username/search query and then walk around this odd gallery.

    If you don't care about the details and just want WolfenFlickr gallery action, go straight to the WolfenFlickr 3D demo page.

    This little experiment killed two birds with one stone. First, I wanted to get to know Flickr's API (and Flickr itself, actually, me not being a big photo nerd). Second, I wanted to do a Javascript raycasting engine. In a moment of unusual clarity, it came to me that these goals were not mutually exclusive and while the end result borders the useless (hey, most things here do), the project served its purpose well.

    WolfenFlickr 3D - Flickr / Wolfenstein 3D JavaScript MashupThe Flickr API part turned out to be pretty simple. The Flickr guys are good people and provide very easy to use methods, JSON data and the option to specify callback JS functions making it a breeze to implement Flickr integration, at least on the level that I'm using here. So, we simply retrieve all photos from a specified user (or matching a search query) to create a list of images for our gallery. For performance reasons, only the first 20 Flickr images are used.

    The Wolfenstein part wasn't all too hard either, although lots of tinkering was needed to make it run semi-smoothly. Unlike the previous JavaScript Wolfenstein 3D experiments here, this one uses a raycasting engine and not the JavaScript 3D engine. If you want to read more about raycasting, check this link or Wikipedia.

    Basically, The screen is divided into X amount of vertical strips (div elements). Each of these strips contains an image element with all the wall textures making the strips serve as containers and masks for the actual lines. "Rays" are then cast out on the map for each strip and when the ray hits a wall, we simply move and scale the wall texture image in the strip according to which wall type, where on the wall the ray hit and how far away it is. Each strip also holds a copy of all the Flickr images positioned on top of the wall textures. Each wall block (with picture frame) is assigned a Flickr image and then it's just a matter of showing the appropriate part of the image on top of the texture. The pictures are stretched (and slightly cropped) to fit the frames, so it looks best with pictures that are not too tall/wide. There are a few things I need to fix and then maybe I'll do a more detailed post on the raycasting part if there's any interest?

    I also tried using canvas just to see what kind of performance that would give. It appeared to be roughly equal to the straight DOM approach but would get complicated (and probably slower) when sprites were added since the current approach utilizes the browser's own fast depth sorting via the z-index on the strips and sprites.

    Tested with FF2, FF3, Opera 9.51, IE7 (IE8b1 doesn't work), Safari 3.3.2. For some reason the recent WebKit nightlies are not working for me at all (crashes on any page, anyone else get that?), but Safari 4 dev preview works fine.
    Safari is awesome and runs very smoothly for me. Opera 9.51 runs ok, IE7 and FF2 a little slower and for some reason FF3 is just horrible slow. Where FF2 takes a hit at the raycasting (ie. pure Javascript) and is quite fast at changing/rendering the DOM elements, it seems FF3 is just the opposite. Maybe I'll give the canvas approach another go and see how FF3 likes that.
    Edit: For better performance in Opera, turn off [Multimedia]->"Interpolate images" in "opera:config" and it should run a lot faster.
    The player position is for some reason not drawn on the minimap in IE (and the map might not render at all). Other than that, there shouldn't be any major problems (aside from speed).

    Take the WolfenFlickr 3D tour!

    Edit: I also found a Youtube video of WolfenFlickr in action. Check it out if you're having trouble with the real thing!

    And do leave a comment if you feel like it.
    Read more...
    YouTube Annotations, round 2 Made a few changes to the annotations script.

    For now, I've scrapped the overlayed annotations since it was just too buggy and unstable. It didn't work reliably in enough browsers for it to be worthwhile and it was pretty meaningless anyway.

    The script now adds a hidden form field which is updated with the current annotation text every time an annotation is added or removed. This should help screen readers know that something changed, I've been told. However, I'm not sure how to handle multiple overlapping annotations, since you wouldn't want the same text read again just because a second annotation is shown. As it is now, all "active" annotations are put in the same form field. Maybe it needs a whole bunch of hidden fields?
    Read more...
    YouTube Annotations and JavaScript YouTube recently added a new annotation feature, but at the moment it's still beta and annotations only show up on youtube.com and not on embedded videos. It's a neat feature in itself, but as Chris Heilmann posted, it would be nice if there was an API available to access those annotations.

    So, I went and looked and made an attempt at accessing and using these annotations with Javascript and embedded videos. The annotations are available as XML data and I've used two lines of PHP to retrieve the XML and feed it raw to the JS. Then my horribly inefficient approach uses a timer with a short interval that runs through all annotations and checks which ones are currently visible. It fires two custom events on the player object when an annotation is either added or removed.
    I even tried to render the annotations on top of the video, but putting DOM stuff on top of Flash isn't always fun. It depends on changing the movie's "wmode" parameter something other than "window" and in some browsers that stalls the timer while the video is playing.

    Only FF3 (maybe FF2?) and Safari can do both the events and the overlayed annotations, it seems.
    I suppose if we just skip the whole overlayed annotations thing and wait for them to show up in embedded videos, everything will be fine.

    Check it out here, but be warned. It's not very stable, and I've managed to make both FF, Opera and IE crash. Reloading the page before loading a new video might help.

    Edit: The overlayed annotations have been scrapped, since it just wasn't stable enough.
    Read more...