Inline (binary) images, data:URIs and canvas tags

In a typical webpage, images are not embedded in the HTML code, but stored as separate files on the server and requested by individual HTTP GET commands. For different reasons it would be useful to include images in the main web document :

  • to speed up the rendering of the webpage in the browser : 80% of the end-user response time is spent on the front-end by downloading all the components in the page: images, stylesheets, scripts, Flash, etc
  • to minimize HTTP requests and to reduce trafic costs (e.g. when using an Amazon webservices pricing model)
  • to display images created by code (e.g. sparklines)
  • to display images retrieved from a database or from a REST service

In august 1998, L. Masinter from Xerox Corporation published a Request for Comment (RFC 2397) for a Uniform Resource Locator (data:URI) scheme that provides a way to include data in line in web pages as if they were external resources. Although the IETF never formally adopted it as a standard, the HTML 4.01 specification refers to the data URI scheme and data URIs have been implemented in most browsers, but not in Internet Explorer before version 8, which is the major problem of this solution.

An example of a red dot picture embedded in HTML is given hereafter :

<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0 vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" /> 

Data URIs may contain whitespace for readability.

Another way to embed images in HTML code is the new element <canvas> which is  part of HTML5 and allows for dynamic scriptable rendering of bitmap images. A tutorial about the canvas tag is available at the Mozilla developer center. As for the data:uri, the canvas tag is not supported by Internet Explorer. ExplorerCanvas developed by Erik Arvidsson brings the same functionality to Internet Explorer. To use this solution, web developers only need to include a single script tag in their existing web pages.

<head><!--[if IE]><script src="excanvas.js"></script><![endif]--></head> 

To get the code working, the following additional javascript is needed :

var el = document.createElement('canvas'); G_vmlCanvasManager.initElement(el);var ctx = el.getContext('2d');

The classic solution to display binary images embedded in HTML code is the following :

<html>
<body>
<img src="myimage.php">
</body>
</html>

The corresponding code for myimage.php is :

<?php
header('Content-type: image/jpeg');
// Create image
$image = imagecreatetruecolor($width,$height);
// pick color for the background
$bgcolor = imagecolorallocate($image, 100, 100, 100);
// fill in the background with the background color
imagefilledrectangle($image, 0, 0, $width, $height, $bgcolor);
// output image to the browser
imagejpeg($image);
// delete the image resource
imagedestroy($image);

Be sure that there is no leading whitespace or blank line before the <?php tag, otherwise the displayed result will be of the form

Garbage

One of the first cross-browser methods for incorporating images into self-contained HTML documents was published by Benn P. Herrera in march 2005.  Two years  ago there was not yet a better method avilable. Today the <canvas> tag and the ExploreCanvas JavaScript seems to be the most promising solution to embed binary images in HTML code.

TrueType, OpenType, EOT, WOFF and SVG Fonts

Last update : February 20, 2001
TrueType is an outline font standard originally developed by Apple Computer in the late 1980s as a competitor to Adobe’s Type 1 fonts used in PostScript. TrueType offers font developers a high degree of control over precisely how their fonts are displayed, right down to particular pixels, at various font heights.

OpenType is a format for scalable computer fonts which is built on TrueType, retaining TrueType’s basic structure and adding many intricate data structures for prescribing typographic behavior.

Other font types are :

  • Embedded OpenType (EOT) fonts are a compact form of OpenType fonts designed by Microsoft for use as embedded fonts on web pages. These files usually use the extension “.eot”.
  • Web Open Font Format (WOFF) is a font format, based on the sfnt file structure (used in TrueType and OpenType fonts) and specifically designed for web use with the @font-face declaration. It was developed by Jonathan Kew (Mozilla Corporation), Tal Leming (Type Supply) Erik van Blokland (LettError).
  • SVG Fonts are supported in the W3C spec (http://www.w3.org/TR/SVG11/fonts.html).

The following links give access to Font libraries :

A @fontface generator is available at the Font Squirrel website. A very useful guide about font embedding has been published by Joshua Johnson on the Six Revisions website. A guide about the Google Font API has been published by Divyang Patel on the same website. How to achieve cross-browser @font-face support is the title of a tutorial published on the website lost in the woods.

Sparklines and SpriteMe

The term Sparkline was proposed by Edward Tufte for small, high resolution graphics embedded in a context of words, numbers, images. Tufte describes sparklines as data-intense, design-simple, word-sized graphics. Sparklines present trends and variations associated with some measurement, such as average temperature or stock market activity, in a simple and condensed way.

A Sparkline PHP Graphing Library has been developed by James Byers who edits alos a wiki about this topic.

jQuery plugin developed by Gareth Watts generates sparklines directly in the browser using data supplied either inline in the HTML, or via javascript.

Joe Gregorio created a sparkline generator. You can start right away by dynamically creating a sparkline using the Sparkline Generator Web Application or you can download the spark.cgi code written in python and running the sparkline service on your own server. Joe Gregorio published a contribution about sparklines (A Bright, Shiny Service: Sparklines) in june 2005. Another sparkline builder has been developed by Mark Pursey. Will Larson created a a simple javascript utility for building sparklines.

Most sparklines are embedded in webpages with data:URIs (RFC 2397) which are not implemented in Internet Explorer lower than version 8. The sparklines are not displayed with those browsers.

Sparklines are also part of the Google Visualization API which works also with Internet Explorer.

Other useful links about sparklines are :

Another technique to reduces the number of downloads in a webpage are sprites. A sprite combines multiple background images into a single image. Steve Souders developed a bookmarklet (javascript file) called SpriteMe to add this functionality to webpages.

Popup window with parameters

If a new window is created by an user action, it will not be blocked by the browser’s popup blocker.

The dimensions (width & height) of the popup window are required, the other parameters are optional:

  • left & top :  the distance from the top and left side of the screen
  • toolbar :  if the popup should have a set of navigation buttons across the top
  • location :  if the popup should have a location bar where the URL is displayed
  • directories :  if the popup should have a row across the top with buttons to popular web sites
  • status : if the popup should have a status bar across the bottom
  • menubar : if the popup should have a menu
  • scrollbars : if the popup should have scroll bars
  • resizable : if users can resize the popup
  • dependent : if the popup should close when its opener window closes
  • full screen : how to open a full screen popup

The popup script has the following format:

window.open(href, windowname,

width=400,height=200,scrollbars=yes’);

An example is given below:

[HTML1]

Web Design : em versus pixel

Last update : June 24, 2014

Because of the wide range of settings and equipment that people might be using to access the web, there is no “best font size”. Font sizes should be specified using relative units like percentage or em since these will allow the user to adjust font sizes up or down to suit their own requirements.

With CSS you can specify font size as a percentage of the font size of a parent element. For example, headings are inside the body of the page. If you don’t set a size for the text in the body, the text of the body will be the size that the reader has chosen as their default size. An ’em’ is equal to the computed value of the ‘font-size’ property of the element on which it is based. The exception is when an ’em’ occurs in the value of the ‘font-size’ property itself, in which case it refers to the font size of the parent element. It may be used for vertical or horizontal measurement.

A default font size of 16 pixels is used for the body if the browsers are configured as follows :

  • Internet Explorer, choose View>Text Size>Medium
  • Opera, choose View>Zoom>100%
  • Firefox, choose View>Text Size>Normal

Some web designers recommend to set the font size in the body to 10 pixels (63%) to allow easier calculations of the em-values (in this case 1.4 em gives a font size of 14 pixels). In the case of embedding elements, this gives no real advantage for the calculations.

em versus pixel

The following table shows the relations between pixels and em’s for different font-sizes, based on a default font size of 16 pixels = 1.0 em.

font-size pixels em
xx-small 9 0,56
x-small 10 0,63
small 13 0,81
medium 16 1,0
large 18 1,13
x-large 24 1,5
xx-large 32 2,0

Lorem Ipsum

Last update : August 19, 2016

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters. More informations about Lorem Ipsum and an online generator are available at the lipsum.com website.

A more recent artisanal filler text generator is Hipster Ipsum. A hipster is a person who follows the latest trends and fashions, especially those regarded as being outside the cultural mainstream. Ian Van Ness, senior hardware tools developer at Apple, created HipsterJesus, an API to create Hipster Ipsum texts related to the bible. Hipster Jesus is an Internet Meme referring to a series of images of a glasses wearing version of Jesus Christ.

class = “notranslate”

Google Translate Widget

Google Translate Widget

If you use the Google Translate widget on your webpages, sometimes there may be some content that you don’t want to translate. You can add class=”notranslate” to any HTML element to prevent that element from being translated. If you have an entire page that should not be translated, you can add:

<meta name=”google” value=”notranslate” />

Prevent caching of dynamically added iframes

I wanted to insert an iframe in a webpage, chosen at random among the files panel_1.html, panel_2.html, panel_3.html.

I first tried to setup the iframe with JavaScript at onload with innerHTML or with document.write in a div container called “content”. An example is shown herafter:

var i = 1 + Math.round(Math.random()*(2));

document.getElementById(‘content’).innerHTML='<iframe src=”panel_’ +i +’.html” width=”100%” height=”100%”></iframe>’;

These solutions worked as expected in the Google Chrome browser, but there were problems either with the Firefox browser or with the IE browser due to caching problems. The iframe was not refreshed despite changing the src data in the iframe tag.

Most proposals found on the web with a Google search did’nt solve the problem on all browsers. By setting the src of the Iframe instead of changing the innerHTML of its container as shown hereafter the iframes are refreshed in the 3 browser’s IE, Firefox and Chrome.

<iframe id=”mypanel” src=”about:blank” width=”100%”
height=”100%” ></iframe>
<script type=”text/javascript”>
var i = 1 + Math.round(Math.random()*(2));
document.getElementById(‘mypanel’).src=’panel_’+i+’.html’
</script>

I would like to add that by using the <object> tag insted of the <iframe> tag, cross-browser problems are even worse.

HTML client-side image maps

Last update : June 24, 2014

You can create different clickable areas within an image using the usemap attribute together with the map tag. The usemap attribute of the img tag points to an map tag containing a description of the clickable areas that the map is divided into. The map tag has a id attribute to define its name, and also declares which areas are clickable by using the area tags.

An example of HTML code is shown below :

<img src="image.jpg"
	width="150"
	height="70"
	usemap="#mymap">
<map id="mymap">
	<area shape="rect"
		   href="start.html"
		   coords="0,0,48,28"
                   alt="blablabla" />

	<area shape="circle"
		   href="previous.html"
		   coords="50,30,10"
                   alt="blablabla" />

	<area shape="poly"
		   href="next.html"
		   coords="60,50,80,30,100,40,50,100"
                   alt="blablabla" />
</map>

The coordinates for the different shapes are :

  • rect (rectangle) : top left x, y ; bottom right x, y
  • circle : center x, y ; radius
  • poly (polygon) : list of x, y coordinates, separated by commas

In XHTML 1.0, the “usemap” attribute in the “img” element is defined as being a URI. This means that # (pound sign) can be used, as it specifies a link to a ‘fragment identifier’ in the current page. For the “map” element, the “id” attribute is required. In XHTML 1.1, the “usemap” attribute for the “map” element is an IDREF rather than a URI. This means that this value must be the same value as the “id” attribute of the other element.

The problem is that the valid code does’nt work in all browsers. If you want an image map that functions, you must write invalid XHTML 1.1 code. More infos about this topic are available at the Randsco website.

The name tag is required besides the id tag for the Firefox and Chrome browser’s. To embed a usemap in another HTML page, the object tag returns a wrong URL with embedded links. A workaround is to use iframes which work in most browsers.

ISMAP is part of the old-fashioned way of making image maps which originally required a server-side file as well as the HTML in the page.

We can add events (that can call a javascript) to the tags inside the image map. The tag supports the onClick, onDblClick, onMouseDown, onMouseUp, onMouseOver, onMouseMove, onMouseOut, onKeyPress, onKeyDown, onKeyUp, onFocus, and onBlur events.

A code example is shown hereafter :

<area shape =”circle” coords =”90,58,3″
onMouseOver=”writeText(‘The mouse is inside the circle.’)”
href =”about.html” target =”_blank” alt=”Blablabla” />

A useful program to set up image maps is Mapedit 4.0 5 from Boutell.com.

Unobtrusive JavaScript

The following HTML code shows the basics of modern javascript programming :

<html>
<head>
<script type=”text/javascript” src=”helloworld.js”></script>
</head>
<body>
<p id=”hello”></p>
</body>
</html>

The concept is to keep the javascript separate from the HTML of the web page and to just use a script tag in the head section of the webpage to link the two together. An id tag is used to identify the part of the body of the web page that should be updated with javascript.

The javascript code is shown below :

function sayHello() {
document.getElementById(‘hello’).innerHTML = ‘Hello World’;
}
window.onload = sayHello;

In the past the function document.write() was used for this purpose, but this is “bad form” and not valid xhtml code. To adhere to strict xhtml code, then it would be better to create elements using document.createElement and element.appendChild (and other native DOM node manipulation functions). For inserting text into an existing element, innerHTML is still acceptable code (and completely cross-browser). The “all DOM” way requires a lot of extra code, is slower, harder to maintain than simpler method and it needs more bandwidth.