Skip to content

Commit

Permalink
fix: fix getBBox function,now support get HTMLElement
Browse files Browse the repository at this point in the history
  • Loading branch information
金强强 authored and bubkoo committed Jun 22, 2020
1 parent 94d5c72 commit 895c02e
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
17 changes: 17 additions & 0 deletions packages/x6/src/util/dom/elem.ts
Expand Up @@ -195,3 +195,20 @@ export function appendTo(elem: Element, target: Element) {
target.appendChild(elem)
}
}

// Determines whether a node is an HTML node
export function isHTMLElement(
elem: any
): elem is HTMLElement {
try {
// Using W3 DOM2 (works for FF, Opera and Chrome)
return elem instanceof HTMLElement
} catch(e) {
// Browsers not supporting W3 DOM2 don't have HTMLElement and
// an exception is thrown and we end up here. Testing some
// properties that all elements have (works on IE7)
return (typeof elem === "object") &&
(elem.nodeType === 1) && (typeof elem.style === "object") &&
(typeof elem.ownerDocument === "object")
}
}
30 changes: 29 additions & 1 deletion packages/x6/src/util/dom/geom.ts
@@ -1,7 +1,8 @@
import { Point, Line, Rectangle, Polyline, Ellipse, Path } from '../../geometry'
import { attr } from './attr'
import { sample, toPath, getPointsFromSvgElement } from './path'
import { ensureId, isSVGGraphicsElement, createSvgElement } from './elem'
import { ensureId, isSVGGraphicsElement, createSvgElement, isHTMLElement } from './elem'
import { getComputedStyle } from './style'
import {
createSVGPoint,
createSVGMatrix,
Expand Down Expand Up @@ -71,6 +72,11 @@ export function getBBox(
// If the element is not an SVGGraphicsElement, we could not measure the
// bounding box either
if (!ownerSVGElement || !isSVGGraphicsElement(elem)) {
if (isHTMLElement(elem)) {
// If the element is a HTMLElement, return the position relative to the body
const { left, top, width, height } = getBoundingOffsetRect(elem as any)
return new Rectangle(left, top, width, height)
}
return new Rectangle(0, 0, 0, 0)
}

Expand Down Expand Up @@ -374,3 +380,25 @@ export function animateAlongPath(
}
}
}

export function getBoundingOffsetRect(elem: HTMLElement) {
let left = 0
let top = 0
let width = 0
let height = 0
if (elem) {
let current = elem as any
while (current) {
left += current.offsetLeft
top += current.offsetTop
current = current.offsetParent
if (current) {
left += parseInt(getComputedStyle(current, 'borderLeft'), 10)
top += parseInt(getComputedStyle(current, 'borderTop'), 10)
}
}
width = elem.offsetWidth
height = elem.offsetHeight
}
return { left, top, width, height }
}

0 comments on commit 895c02e

Please sign in to comment.