Introduction

edit

Images can be available in the DOM (Document Object Model) of the browser in mainly to ways:

  • in an img tag
  • in a canvas tag

Image Tag

edit

The img is used for images that you might want

  • to scale in size,
  • change the alignment (left, right, center) of the image on page,
  • extract the image size (width and height) of loaded image and display the size in the text
  • ...

with Javascript.

Canvas Tag

edit

The canvas tag provides (as you might already assume by the name) options to

  • modify loaded images on the pixel level (e.g. exchange a red pixel on the canvas by a blue pixel),
  • mark specific areas on the image and annotate the image with
    • text (e.g. add the name of the building on the image),
    • geometric objects (e.g. mark a person with a circle or add an arrow in the image, ...
    • merge two source images in one image with a canvas.

Workflow

edit
 
Golden Gate Bridge
 
Brandenburg Gate in Berlin

Workflow with images has the following main steps:

  • (S1) Assignment: to work in Javascript with an image/canvas it is necessary to have a variable in Javascript to work with the image/canvas.
  • (S2) Processing: to select in Javascript the available methods to handle/process images in img or canvas tag
  • (S3) Load/Save (locally): if images are modified on a canvas the result must be provided and converted, so that they result can be submitted to a server or stored locally on a client for further use

For the workflow mentioned above, we will use the image processing workflows as examples.

  • get information about an image with Javacript.
  • load one image into a canvas and add annotation of text or geometric elements like lines, circles and boxes to the image and export the modified image again,
  • load two images and merge them together in a canvas.

As example images we will use the creative commons images of

  • the Golden Gate Bridge in San Francisco and
  • the Brandenburg Gate in Berlin.

Assignment

edit

For an assignment of an image variable it is recommended to use a unique meaningful identfier (id) for the image or canvas, with which you can access the information about the inage or modify the image in the canvas later. This is a standard procedure using document.getElementById(pID) call with the respective identifier pID.

<!DOCTYPE html>
<html>
<body>

<img id="myImage" src="Golden_Gate_Bridge_as_seen_from_Battery_East.jpg" alt="Golden Gate Bridge">

<script>
  var var4image = document.getElementById("myImage");
</script>

</body>
</html>

In the previous example we assume that you have a file index.html and the image Golden_Gate_Bridge_as_seen_from_Battery_East.jpg in one directory.


Adding an Image to HTML Page

edit

The image is added to the HTML as usual with the img tag.

 <img id="myImage" src="Golden_Gate_Bridge_as_seen_from_Battery_East.jpg" >

The important aspect to mention is, that all images have a unique ID in the DOM of your HTML page. So having more images in one page you have to assign a new identifier to each image.

 <img id="myImage" src="Golden_Gate_Bridge_as_seen_from_Battery_East.jpg">
 <img id="myImage2" src="Brandenburger_Tor_abends.jpg">

To make the Javascript code more readable and maintainable you might want to assign meaning identifiers to image. As an example we change the identifier of the second image to a meaningful name.

 <img id="myImage" src="Golden_Gate_Bridge_as_seen_from_Battery_East.jpg">
 <img id="imgBrandenburgGate" src="Brandenburger_Tor_abends.jpg">

A prefix img... might be used for the identifier imgBrandenburgGate that indicates the id refers to an image and not in a canvas. Now we add also a canvas to the HTML code. The canvas has a specific a specific width and size. Due to the fact that the canvas is empty we must specific the size of the canvas with width and height attribute that you can use with images as well.

 <img id="myImage" src="Golden_Gate_Bridge_as_seen_from_Battery_East.jpg">
 <img id="imgBrandenburgGate" src="Brandenburger_Tor_abends.jpg">
 <canvas id="canvImageAnnotation" width="320" height="213"></canvas>

Assigning the Image Variable

edit

The following Javascript code assigns the img object in the DOM of the HTML page to the variable var4image.

 var var4image = document.getElementById("myImage");

Especially in more complex code you might want to use meaningful variable names in your Javascript code as well, similar to the identifiers in the DOM. We use meaningful names for the second image and the canvas.

 var var4image = document.getElementById("myImage");
 var imgGate = document.getElementById("imgBrandenburgGate");
 var canvas4annotation = document.getElementById("canvImageAnnotation");

Error Handling for Image Assignment

edit

Keep in mind that an image with identifier might not exist in the DOM tree and then the image variable is null. This might be handled with a getImage4Id(pID) function.

 function getImage4Id(pID) {
   var vImg;
   if (pID) {
      vImg = document.getElementById(pID);
      if (vImg) {
        return vImg;
      } else {
         console.error("Image with identifier '" + pID + "' does not exist in the DOM tree.");
      }
   } else {
     console.error("No identifier 'pID' was provided for function call getImage4ID()");
   }

Once the function is defined you can replace the document.getElementById(...) by an getImage4Id(...).

 var var4image = getImage4Id("myImage");

You might want to use the function getImage4Id(...) in multiple HTML projects so we assume to aggregate all the function that we want to reuse in a Javascript file imagehandlers.js stored in a subdirectory "js/.

Processing

edit

For the processing we assume you have a folder LearnJavacript/ on your computer with the subdirectories img/, js/ and css/.

  • the subdirectory img/ contains all the images that we use in the examples for images processing,
  • the subdirectory js/ contains Javascript code that we use e.g. in multiple examples for images processing,
  • the subdirectory css/ contains style sheet file the define the layout of the canvas or the image that we alter we Javascript according to the learning task.

Images and Canvas Tags

edit

For the reduction of the code length we rename and shorten the image names given from Wiki Commons for both example images about Golden Gate Bridge and the Brandenburg Gate. So move both examples to the img/ subdirectory of the folder LearnJavacript/ folder and name them

  • ggbridge.jpg for the Golden Gate Bridge and
  • bbgate.jpg for the Brandenburg Gate.

So we change the code fragments mentioned above for the image definition as follows

 <img id="imgBridge" src="img/ggbridge.jpg" width="320" height="200" >
 <img id="imgGate"   src="img/bbgate.jpg"   width="320" height="213" >
 <canvas id="canvImageAnnotation" width="640" height="213"></canvas>

Javascript Function to merge Images

edit

As you might assume from the image sizes, we want combine both images next to each other on the canvas "canvImageAnnotation" and have 13 pixel height empty space on the canvas below the Golden Gate Bridge. The width of the canvas "canvas1" is 640 pixel and the height was chosen as maximum of both heights of both source images.

  function mergeImage() {
    var canvas1 = document.getElementById("canvImageAnnotation");
    var ctx=canvas1.getContext("2d");
    var image1 = document.getElementById("imgBridge");
    var image2 = document.getElementById("imgGate");
    ctx.drawImage(image1, 0, 0, 320, 200);
    ctx.drawImage(image2, 321, 0, 320, 213);
 };

Button to Execute Image Merge

edit

Now we assign the function mergeImage() to an onclick event of a button.

 <button onclick="mergeImage();return false" >Merge 2 Images </button>

Load/Save

edit

In the next step an image from the local filesystem should be loaded into the browser locally (not on a remote server - see AppLSAC). The following steps are included and applied to a HTML canvas because the user should be able to annotate the image e.g. with a red circle to mark or highlight a specific area on the image:

  1. Create a HTML page imagehandler.html with header and body
  2. create Javascript file js/imageloadsave.js in a js subfolder, that contains the used Javascript libraries,
  3. add file button to HTML page imagehandler.html, that creates a file dialog for the user to select and load an image from the local hard disk,
  4. assign an event handler to the file button, that checks if the loaded file is an image,
  5. resize a canvas to 90% of window width and calculate the height of the canvas according to aspect ratio of the image.
  6. modify the image and paint a red circle on the loaded image,
  7. save the image to PNG, JPG, SVG to the download folder (see AppLSAC/Save).