A hover effect can grow stronger as the pointer moves away from an element’s center. Distance gives that movement a number: zero at the center, increasing toward the edges. The same calculation helps animate elements, recognize touch gestures, and detect pointer hits on curved charts. section 10.2.3 section 13.1.2 section 14.1.3
For two points, subtract their x-coordinates to get dx and their y-coordinates to get dy. The straight-line distance is `Math.sqrt(dx * dx + dy * dy)`. This is the Pythagorean theorem applied to the horizontal and vertical gaps. Before comparing pointer coordinates with an element or canvas, account for where that object sits in the viewport. section 13.1.2 section 13.5
What can that number control?
- Hover intensity: measure from the element center to the mouse. Divide by the center-to-corner distance to scale rotation and zoom; the illustrated zoom rises from 1 at the center to 1.05 at the edge. section 10.2.3
- Movement toward a click: find the magnitude of the vector from the element to its target. Move by a fixed-speed step while the remaining distance exceeds that speed, then snap to the target. section 10.3.3
- Pinch zoom: measure the distance between two touch points on each move. Divide it by their starting distance to obtain a photo’s scale, clamped between 0.5 and 5. section 13.1.2
- Donut-chart hits: measure from the chart center to the pointer. Only points between the inner and outer radii qualify; an angle check then identifies the slice. section 14.1.3
Listing 14.3c Creating an interactive donut chart (part 3)
canvas.addEventListener('pointermove', (e) => {
const rect = canvas.getBoundingClientRect(); #1
const pointerX = e.clientX - rect.left; #1
const pointerY = e.clientY - rect.top; #1
const dx = pointerX - centerX; #2
const dy = pointerY - centerY; #2
const distance = Math.sqrt(dx * dx + dy * dy); #3
let currentSliceIndex = null;
if (distance >= innerRadius &&
➥ distance <= outerRadius) { #4
let pointerAngle = Math.atan2(dy, dx); #5
if (pointerAngle < -0.5 * Math.PI) {
pointerAngle += 2 * Math.PI; #6
}
seawaterData.forEach((slice, index) => { #7
if (pointerAngle > slice.startAngle &&
pointerAngle < slice.endAngle) {
currentSliceIndex = index; #8
}
});
}
if (activeSlice !== currentSliceIndex) {
activeSlice = currentSliceIndex;
if (activeSlice !== null) {
const s = seawaterData[activeSlice]; #9
descriptionTitle.textContent = #9
`${s.label} (${s.value}%)`; #9
descriptionText.textContent = s.desc; #9
} else { #10
descriptionTitle.textContent = ''; #10
descriptionText.textContent = 'Hover over a slice #10
for details.'; #10
}
}
});
drawChart(); #11
The pointer-move handler converts viewport coordinates to canvas coordinates, calculates center-to-pointer distance, checks the donut’s radii, and then tests slice angles. section 14.1.3









