Friday, March 29, 2024

HTML5 Image Attributes and Features Explained

Images are without a doubt the number one low-tech way to add pizazz and color to an otherwise lackluster web page. I can still remember my excitement upon creating my first mouseover image swap. It was like reading a magazine, except one that reacted to my actions.

Mouseover effects notwithstanding, there were a number of limitations to using images in web pages, one of the most salient being that there was no way to semantically associate an image with its caption. Well, that’s all changed with HTML5. In fact, you won’t believe some of the nifty things that you can do with images now!

What’s Out and What’s In

The align, border, hspace, and vspace layout attributes were deprecated in HTML 4.01, and are no longer supported in HTML5. However, alt, src, height, width, ismap, usemap, as well as event-related attributes are still alive and well. There has also been talk of a longdesc attribute for use when the text in the image is more than can fit in the alt. The longdesc would provide a link to a page with a more detailed description. However, it is not supported by any browser at this time. The attributes that have been deprecated are those which could presumably be covered by CSS rules. The height and width are still necessary because they tell the browser how much space to allocate on the page for the image. You do always include them right?

New Elements: Figure and Figcaption

Getting back to the captions issue, HTML5 introduces two elements that work in tandem to add captions and other text details to diagrams, illustrations, photos, code examples, and pretty much any other visual element that you can think of. You’ll also be happy to know that they are supported by ALL the major browsers!

Here’s how it works: The <figure> element encloses both the image and caption, if you include one. You see, the <figcaption> element is optional, so you can have an image without one. I’m not sure what the advantage would be to enclosing your image in a <figure> tag without a caption, but there is nothing stopping you from doing so. Only one <figcaption> element may be nested within a <figure>, although the <figure> element itself may contain other child elements, such as <img> or <code>, and can appear before or after the content within the <figure>. Here’s an example:

<figure>
  <img id="robAtGreenfields" src="Rob_at_Greenfields.jpg" alt="Rob at Greenfields" width="342" height="514"
	 style="border: 3px outset gray;">
	  <figcaption style="clear: left;margin: .75em 0;text-align: center;font-style: italic;line-height: 1.5em;"
		<br/>>I am an IT expert, but I want to be a rock star!
    <br>Image courtesy of <a href="http://www.christopp.ca/home.htm">Chris Topp Photography</a></figcaption>
</figure>

The Canvas Element

The Canvas tag is a new HTML element which for drawing graphics using a scripting language such as JavaScript. It can be used to draw graphs, make photo compositions or even animations. Moreover, it’s a great tool for creating eye-catching image filter effects.

Here’s a functions to retrieve an image’s pixels:

function getPixels(img) {
	var c = document.createElement('canvas');
	with (c) { width = img.width; height = img.height; }
  var ctx = c.getContext('2d');
  ctx.drawImage(img);
  return ctx.getImageData(0,0,c.width,c.height);
};

The following code applies a grayscale filter on an image:

function grayscale(img) {
  var d = getPixels(img).data;
  for (var i=0; i<d.length; i+=4) {
    var r = d[i];
    var g = d[i+1];
    var b = d[i+2];
    // CIE luminance for the RGB
    var v = 0.2126*r + 0.7152*g + 0.0722*b;
    d[i] = d[i+1] = d[i+2] = v
  }
  return pixels;
};

That’s the basic code. The HTML5Rocks site has a more complete code listing to achieve the grayscale and several other cool image effects.

Cropping an Image

The key to cropping an image using the HTML5 Canvas is the drawImage() method. It accepts an image object, plus six additional parameters: sourceX, sourceY, sourceWidth, sourceHeight, destWidth and destHeight. We can use these parameters to define the exact location and size of a rectangle that we want to crop from the larger image:

 context.drawImage(imageObj, sourceX, sourceY, sourceWidth,
	sourceHeight, destX, destY, destWidth, destHeight); 

Here’s some code that uses the window and image’s onload events to display a cropped version of the above image when the page loads. All you need is a <canvas> tag in which to put the image:

<script type="text/javascript">
window.onload = function(){
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
 
    var imageObj = new Image();
    imageObj.onload = function(){
        // draw cropped image
        var sourceX = 80;
        var sourceY = 0;
        var sourceWidth = 150;
        var sourceHeight = 270;
        var destWidth = sourceWidth;
        var destHeight = sourceHeight;
        var destX = canvas.width / 2 - destWidth / 2;
        var destY = canvas.height / 2 - destHeight / 2;
 
        context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
    };
    imageObj.src = "Rob_at_Greenfields.jpg";
};
</script>
</head>
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>

Conclusion

That’s a mere taste of what you can do with images. Other effects include drag & drop, image resizing, cloning, inverting, animation, sharpening & blurring effects, and more! For instance, here’s an oscillating bubble animation that moves with amazingly fluidity! Remember to use the Modernizr library to make sure that browsers support the canvas object and its attributes. You may also want to think of how to present the content to people using older browsers.

Robert Gravelle
Robert Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured