Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(canvas): fix getRelativeCursor for non SVG implementations #2125

Merged
merged 1 commit into from
Sep 11, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 32 additions & 10 deletions packages/core/src/lib/interactivity/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,39 @@

export * from './detect'

/**
* Get the position of the cursor (from `event`) relative
* to its container (`el`).
*
* In a normal situation mouse enter/leave events
* capture the position ok. But when the chart is inside a scaled
* element with a CSS transform like: `transform: scale(2);`
* tooltip are not positioned ok.
*
* Comparing original width `box.width` against the scaled width
* give us the scaling factor to calculate the proper mouse position.
*/
export const getRelativeCursor = (el, event) => {
const { clientX, clientY } = event
const bounds = el.getBoundingClientRect()
const box = el.getBBox()
// Get the dimensions of the element, in case it has
// been scaled using a transform for example, we get
// the scaled dimensions, not the original ones.
const currentBox = el.getBoundingClientRect()

// Original dimensions, necessary to compute `scaleFactor`.
let originalBox
if (el.getBBox !== undefined) {
// For SVG elements.
originalBox = el.getBBox()
} else {
// Other elements.
originalBox = {
width: el.offsetWidth,
height: el.offsetHeight,
}
}

// In a normal situation mouse enter / mouse leave events
// capture the position ok. But when the chart is inside a scaled
// element with a CSS transform like: `transform: scale(2);`
// tooltip are not positioned ok.
// Comparing original width `box.width` agains scaled width give us the
// scaling factor to calculate ok mouse position
const scaling = box.width === bounds.width ? 1 : box.width / bounds.width
return [(clientX - bounds.left) * scaling, (clientY - bounds.top) * scaling]
const scaleFactor =
originalBox.width === currentBox.width ? 1 : originalBox.width / currentBox.width
return [(clientX - currentBox.left) * scaleFactor, (clientY - currentBox.top) * scaleFactor]
}