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();
14 if (clientRects
.length
== 0) {
15 var box
= element
.getBoundingClientRect();
16 if (element
.tagName
.toLowerCase() == 'area') {
17 var coords
= element
.coords
.split(',');
18 if (element
.shape
.toLowerCase() == 'rect') {
19 if (coords
.length
!= 4)
20 throw new Error('failed to detect the region of the area');
21 var leftX
= Number(coords
[0]);
22 var topY
= Number(coords
[1]);
23 var rightX
= Number(coords
[2]);
24 var bottomY
= Number(coords
[3]);
28 'width': rightX
- leftX
,
29 'height': bottomY
- topY
31 } else if (element
.shape
.toLowerCase() == 'circle') {
32 if (coords
.length
!= 3)
33 throw new Error('failed to detect the region of the area');
34 var centerX
= Number(coords
[0]);
35 var centerY
= Number(coords
[1]);
36 var radius
= Number(coords
[2]);
38 'left': Math
.max(0, centerX
- radius
),
39 'top': Math
.max(0, centerY
- radius
),
43 } else if (element
.shape
.toLowerCase() == 'poly') {
44 if (coords
.length
< 2)
45 throw new Error('failed to detect the region of the area');
46 var minX
= Number(coords
[0]);
47 var minY
= Number(coords
[1]);
50 for (i
= 2; i
< coords
.length
; i
+= 2) {
51 var x
= Number(coords
[i
]);
52 var y
= Number(coords
[i
+ 1]);
53 minX
= Math
.min(minX
, x
);
54 minY
= Math
.min(minY
, y
);
55 maxX
= Math
.max(maxX
, x
);
56 maxY
= Math
.max(maxY
, y
);
65 throw new Error('shape=' + element
.shape
+ ' is not supported');
75 var clientRect
= clientRects
[0];
76 var box
= element
.getBoundingClientRect();
78 'left': clientRect
.left
- box
.left
,
79 'top': clientRect
.top
- box
.top
,
80 'width': clientRect
.right
- clientRect
.left
,
81 'height': clientRect
.bottom
- clientRect
.top