Using Javascript to place text on an image

This examples follows on from the mouse coordinates example which showed the Javascript code used in the browser to find the position of the mouse on an image. Instead of displaying the mouse coordinates, they are sent to an ASP script which uses csImageFile to generate an image. The coordinates are passed in the query string as well as the text from the input box.

Click on the image to place the text.

Enter text:

The Javascript code

The Javascript code in the page header is similar to the previous example. The FindPosition function is used to find the position of the image tag, and the GetCoordinates function then finds the coordinates of the mouse when it is clicked on the image. The following line sends the coordinates to the ASP script and the resulting image is displayed. The Javascript function encodeURI is used to encode spaces and any extended characters that use UTF-8 encoding (characters with accents).

myImg.src = "mousetext.asp?x=" + PosX + "&y=" + PosY + "&imagetext=" +
  encodeURI(document.form1.imagetext.value);

The input box is in a form called form1 and is named imagetext. The image tag has an id of myImgId.

<img id="myImgId" alt="" src="red.gif" width="400" height="300" />

The ASP script that creates the image and the text

This script uses the csImageFile component to create an image. It reads the query string to get the coordinates and text and uses the csImageFile Text method to draw the text at those coordinates. The image is streamed to the browser as a GIF.

Set Image = Server.CreateObject("csImageFile.Manage")
Image.NewImage 400, 300, "FF0000"

Image.TextOpaque = false
Image.TextSize = 18

X = CInt(Request.Querystring("x"))
Y = CInt(Request.Querystring("y"))
Text = Image.DecodeUTF8(Request.Querystring("ImageText"))
If X <> 0 Then
  Image.Text X, Y, Text
End If

Response.ContentType = "image/gif"
Response.BinaryWrite Image.GIFData

Some properties are set to control the text appearance. The image is created new, but it could just as easily be loaded from a file on the server. The DecodeUTF8 method is used to reverse the encoding of the Javascript encodeURI function. The image is not saved after displaying.

This technique can be adapted to save the image, or position other features. We have a downloadable example that selects two pairs of coordinates and draws a rectangle on the image.