faqts : Computers : Programming : Languages : JavaScript : Images

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

15 of 15 people (100%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How can I color a rectangle in an image?
How can I color a rectangle in an image?

Oct 10th, 2003 07:40
Michel Plungjan, Martin Honnen,


NN4, NN6 and IE4+ allow to dynamically create a layer, color it and 
place it on top of the IMG at the desired position
Be aware that using background color, the layer will only print if the 
browser is set to print background colors:
<HTML>
<HEAD>
<SCRIPT>
var c = 0;
function coloredRectangle (img, left, top, width, height, color) {
  if (document.layers) {
    var l = new Layer(width);
    l.left = img.x + left;
    l.top = img.y + top;
    l.clip.width = width;
    l.clip.height = height;
    l.bgColor = color;
    l.visibility = 'show';
    return l;
  }
  else if (document.all && !window.opera) {
    var coords  = getImageCoords(img);
    var html = '';
    html += '<SPAN ID="cr' + c + '"';
    html += ' STYLE="position: absolute;';
    html += '        left: ' + (coords.x + left) + 'px;';
    html += '        top: ' + (coords.y + top) + 'px;';
    html += '        width: ' + width + 'px;';
    html += '        height: ' + height + 'px;';
    html += 
     '        clip: rect(auto ' + width + 'px ' + height + 'px auto);';
    html += '        background-color: ' + color + ';';
    html += '       "';
    html += '><\/SPAN>';
    document.body.insertAdjacentHTML('beforeEnd', html);
    return document.all['cr' + c++];
  }
  else if (document.createElement) {
    var coords  = getImageCoords(img);
    var l = document.createElement('SPAN');
    l.id = 'cr' + c++;
    l.style.position = 'absolute';
    l.style.left = (coords.x + left) + 'px';
    l.style.top = (coords.y + top) + 'px';
    l.style.width = width + 'px';
    l.style.height = height + 'px';
    l.style.backgroundColor = color;
    document.body.appendChild(l);
    return l;
  }
}
function getImageCoords (img) {
  var x = 0;
  var y = 0;
  var el = img;
  do {
    x += el.offsetLeft;
    y += el.offsetTop;
  }
  while ((el = el.offsetParent));
  return {x: x, y: y};
}
</SCRIPT>
</HEAD>
<BODY>
<A HREF="javascript: void 0"
   ONCLICK="coloredRectangle(document.imageName, 0, 0, 30, 30, 'white');
            return false;"
>
white rectangle at 0, 0
</A>
|
<A HREF="javascript: void 0"
   ONCLICK="coloredRectangle(document.imageName, 28, 25, 5, 5, 'red');
            return false;"
>
red rectangle
</A>
<BR>
Kibology for all.
<IMG NAME="imageName" SRC="kiboInside.gif">
</BODY>
</HTML>