實現如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#ball {
width: 100px;
height: 100px;
box-sizing: border-box;
border-radius: 50%;
border-color: white black white black;
border-width: 50px;
border-style: solid;
box-shadow: 0 0 2px 1px rgba(0, 0, 0, 1);
}
#rect {
width: 300px;
height: 300px;
border: 1px solid gray;
position: relative;
}
#rect:after{
content: "";
display: block;
position: absolute;
width: 424.3px;
border-bottom: 1px dashed gray;
top: 150px;
left: -62.15px;
transform: rotateZ(135deg);
}
</style>
</head>
<body>
<div id="ball"></div>
<div id="rect"></div>
</body>
<script>
let x = rect.clientWidth,
y = rect.clientHeight,
r = Math.pow(x * x + y * y, 1 / 2),
sinA = y / r, cosA = x / r;
rect.onmousemove = function (e) {
let x1 = e.offsetX,
y1 = y - e.offsetY,
r1 = Math.pow(x1 * x1 + y1 * y1, 1 / 2),
sinA1 = y1 / r1, cosA1 = x1 / r1;
let h = r1 * sinA1 * cosA - r1 * cosA1 * sinA;
rect.innerText = h.toFixed(2);
}
</script>
</html>