Entry
Is it possible to generate graphics with JavaScript?
Can I embed an image in my HTML, not as a separate file?
Jan 8th, 2002 09:41
David Blackledge, http://www.javaworld.com/javaworld/jw-08-1996/jw-08-javascript_p.html (about halfway down: "Creating graphics on-the-fly with JavaScript") http://David.Blackledge.com/XBMCreator.html
A neat trick with images is to use a javascript: URL for your image.
When you do this the browser uses the returned result as the CONTENTS of
the image, rather than the new URL to the image. (The same thing applies
when you use javascript: as a URL in a link, unless the action replaces
the current document, or ends in a voided statement).
What this means is if you can generate the content for an image format,
you can include it embedded in your page, not as a separate file.
How do you generate the content for an image? Well, there is one format
that is easy to generate, and is supported by all browsers since it was
the very first image format supported on the web: XBM.
This image format is actually a C-style declaration of a simple bitmap.
This means two things: it's monochrome (black and white, or black and
clear, depending on the browser version), and it's plain text, so it's
easy to generate.
A quick summary of the format is:
#define ::imagename::_width ::image width::
#define ::imagename::_height ::image height::
static char ::imagename::_bits[] = {
::Bit data in hex. Enough to cover width*height pixels e.g. 0xFF, 0xFC,
...::
};
If you get your image data in that format in a string (complete with the
\n after each of the #define lines), then you can make any image's SRC
attribute be:
"javascript:'"+xbmimagestring+"'"
This can be in-line in the IMG tag, or you can do it later in
Javascript. Any other javascript: specification that results in the
string would work as well.
Again, the XBM format is supported by all browsers, technically, though
Netscape 3.0 seems to interpret the data a little differently than
Netscape 4 and IE. Also note that the bit data is... "little endian?"
Specifically, each 8-bit sequence needs to be in the reverse order from
what you'd expect.
See the "XBMCreator" URL above for an example in action.
Technically, any image format should work with this trick, but others
are harder to generate. The XPM format is a color version of XBM and
is similarly as easy to generate, but it is not widely supported by
browsers, unfortunately.
David.
http://David.Blackledge.com