1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 function getElementRegion(element) {
6 // Check that node type is element.
7 if (element.nodeType != 1)
8 throw new Error(element + ' is not an element');
10 // We try 2 methods to determine element region. Try the first client rect,
11 // and then the bounding client rect.
12 // SVG is one case that doesn't have a first client rect.
13 var clientRects = element.getClientRects();
15 // Element area of a map has same first ClientRect and BoundingClientRect
16 // after blink roll at chromium commit position 290738 which includes blink
17 // revision 180610. Thus handle area as a special case.
18 if (clientRects.length == 0 || element.tagName.toLowerCase() == 'area') {
19 var box = element.getBoundingClientRect();
20 if (element.tagName.toLowerCase() == 'area') {
21 var coords = element.coords.split(',');
22 if (element.shape.toLowerCase() == 'rect') {
23 if (coords.length != 4)
24 throw new Error('failed to detect the region of the area');
25 var leftX = Number(coords[0]);
26 var topY = Number(coords[1]);
27 var rightX = Number(coords[2]);
28 var bottomY = Number(coords[3]);
32 'width': rightX - leftX,
33 'height': bottomY - topY
35 } else if (element.shape.toLowerCase() == 'circle') {
36 if (coords.length != 3)
37 throw new Error('failed to detect the region of the area');
38 var centerX = Number(coords[0]);
39 var centerY = Number(coords[1]);
40 var radius = Number(coords[2]);
42 'left': Math.max(0, centerX - radius),
43 'top': Math.max(0, centerY - radius),
47 } else if (element.shape.toLowerCase() == 'poly') {
48 if (coords.length < 2)
49 throw new Error('failed to detect the region of the area');
50 var minX = Number(coords[0]);
51 var minY = Number(coords[1]);
54 for (i = 2; i < coords.length; i += 2) {
55 var x = Number(coords[i]);
56 var y = Number(coords[i + 1]);
57 minX = Math.min(minX, x);
58 minY = Math.min(minY, y);
59 maxX = Math.max(maxX, x);
60 maxY = Math.max(maxY, y);
69 throw new Error('shape=' + element.shape + ' is not supported');
79 var clientRect = clientRects[0];
80 var box = element.getBoundingClientRect();
82 'left': clientRect.left - box.left,
83 'top': clientRect.top - box.top,
84 'width': clientRect.right - clientRect.left,
85 'height': clientRect.bottom - clientRect.top