2 回答

TA貢獻1804條經驗 獲得超7個贊
如果要計算長度,可以使用以下函數:
// angle: 0-360. 0 = 12 o'clock, 90 = 3 o'clock, ...
// top: the distance of the center to the top side
// right: the distance of the center to the right side
// bottom: the distance of the center to the bottom side
// left: the distance of the center to the left side
function getLength(angle, top, right, bottom, left) {
var sideToCompare1;
var sideToCompare2;
if (angle >= 0 && angle < 90) {
sideToCompare1 = top;
sideToCompare2 = right;
}
else if (angle >= 90 && angle < 180) {
sideToCompare1 = right;
sideToCompare2 = bottom;
angle -= 90;
}
else if (angle >= 180 && angle < 270) {
sideToCompare1 = bottom;
sideToCompare2 = left;
angle -= 180;
}
else {
sideToCompare1 = left;
sideToCompare2 = top;
angle -= 270;
}
// change to radian
angle = angle / 180 * Math.PI;
return Math.min(sideToCompare1 / Math.cos(angle),
sideToCompare2 / Math.sin(angle)); //Math.cos(Math.PI / 2 - angle)
}
函數中的想法是取到時鐘指針將穿過的垂直或水平邊的最小距離。
通過旋轉,四個象限的計算是相同的。這就是if.
注意cos(90-a) = sin(a)。這用于簡化到每個象限第二邊的距離。
如果你想要一個填充到盒子的邊界,你可以考慮垂直于盒子側面或手方向的填充。在第一種情況下,您只需通過所需的填充減少輸入參數。在第二種情況下,只需從該函數的結果中減去填充。

TA貢獻1875條經驗 獲得超5個贊
你總是可以(從字面上)隱藏復雜性。
Math.random.between = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
const createWeb = (el) => {
const clock = {
$canvas: el,
logicalCenter: [Math.random.between(100, 400), Math.random.between(100, 400)],
segments: 12,
};
clock.segmentSize = (Math.PI * 2) / clock.segments;
clock.$canvas.width = 500;
clock.$canvas.height = 500;
clock.ctx = clock.$canvas.getContext('2d');
clock.ctx.strokeStyle = 'orangered';
clock.ctx.lineWidth = 5;
clock.ctx.fillStyle = 'white';
const draw = {
arm: (atSegment) => {
atSegment = atSegment % clock.segments;
const degree = atSegment * clock.segmentSize;
const handLength = clock.$canvas.width * 2;
const [x, y] = [Math.cos(degree) * handLength, Math.sin(degree) * handLength];
clock.ctx.beginPath();
clock.ctx.moveTo(...clock.logicalCenter);
clock.ctx.lineTo(x + clock.logicalCenter[0], y + clock.logicalCenter[1]);
clock.ctx.stroke();
},
center: (radius) => {
clock.ctx.beginPath();
clock.ctx.arc(...clock.logicalCenter, radius, 0, Math.PI * 2);
clock.ctx.stroke();
},
border: (thickness) => {
const [w, h] = [clock.$canvas.width, clock.$canvas.height];
clock.ctx.fillRect(0, 0, thickness, h);
clock.ctx.fillRect(0, 0, w, thickness);
clock.ctx.fillRect(0, h - thickness, w, thickness);
clock.ctx.fillRect(w - thickness, 0, thickness, h);
}
};
draw.center(10);
Array(clock.segments).fill(0)
.map((_, i) => i)
.forEach(draw.arm);
draw.border(20);
}
document.querySelectorAll('.clock').forEach(createWeb);
* {
margin: 0;
padding: 0;
}
.clock {
position: relative;
width: 200px;
height: 200px;
border: 3px orangered solid;
box-sizing: border-box;
}
<canvas class="clock"></canvas>
<canvas class="clock"></canvas>
<canvas class="clock"></canvas>
添加回答
舉報