如何在p5.js中识别弧线内的光标?
我正在制作一个饼图,希望当光标移动到我的分段上时突出显示,然后在用户单击分段时展开。我看过许多关于如何让圆形或正方形识别光标位于其空间内的教程,但对于可以根据值输入改变大小的圆弧,我没有什么能理解的。
以下是我设置图表的方式:
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">chartX = 250;
chartY = 250;
chartW = 250;
chartH = 250;
// Movie Genres
com = 32;
act = 52;
rom = 40;
dra = 18;
sci = 26;
totalMovies = com+act+rom+dra+sci;
function setup() {
createCanvas(500, 500);
background(255);
}
function draw() {
startAngle = 0;
totalRadians = TWO_PI;
// Pie Chart
noFill();
ellipse(chartX, chartY, chartW);
fill(38,70,83);
arc(chartX, chartY, chartW, chartH, startAngle, (totalRadians/(totalMovies/com)),PIE);
startAngle = (totalRadians/(totalMovies/com));
fill(42,157,143);
arc(chartX, chartY, chartW, chartH, startAngle, startAngle + (totalRadians/(totalMovies/act)),PIE);
startAngle+=(totalRadians/(totalMovies/act));
fill(233,196,106);
arc(chartX, chartY, chartW, chartH, startAngle, startAngle + (totalRadians/(totalMovies/rom)),PIE);
startAngle+=(totalRadians/(totalMovies/rom));
fill(244,162,97);
arc(chartX, chartY, chartW, chartH, startAngle, startAngle + (totalRadians/(totalMovies/dra)),PIE);
startAngle+=(totalRadians/(totalMovies/dra));
fill(231,111,81);
arc(chartX, chartY, chartW, chartH, startAngle, startAngle + (totalRadians/(totalMovies/sci)),PIE);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js" integrity="sha512-N4kV7GkNv7QR7RX9YF/olywyIgIwNvfEe2nZtfyj73HdjCUkAfOBDbcuJ/cTaN04JKRnw1YG1wnUyNKMsNgg3g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
解决方案
假设饼图分段定义为一系列角度,并且饼图切片来自固定方向,则可以使用从饼图中心到鼠标光标的水平和垂直偏移量,然后使用三角函数来查找从饼图中心到鼠标光标的直线与水平轴之间的角度。然后,可以使用该角度来确定鼠标所在的饼图段。您要使用的特定三角函数是arc tangent(也称为atan、逆切线或tan⁻?),而特定的p5.js函数是atan2()
。
const colorNames = ['red', 'green', 'blue'];
const radius = 80;
let segments = [ 34, 55, 89 ];
let angles;
let colors;
let centerX, centerY;
function setup() {
createCanvas(windowWidth, windowHeight);
ellipseMode(RADIUS);
angleMode(DEGREES);
noStroke();
let total = segments.reduce((v, s) => v + s, 0);
angles = segments.map(v => v / total * 360);
colors = colorNames.map(n => color(n));
centerX = width / 2;
centerY = height / 2;
}
function draw() {
background(255)
let start = 0;
let mouseAngle = atan2(mouseY - centerY, mouseX - centerX);
if (mouseAngle < 0) {
mouseAngle += 360;
}
let mouseDist = dist(centerX, centerY, mouseX, mouseY);
for (let ix = 0; ix < angles.length; ix++) {
let hover = mouseDist < radius && mouseAngle >= start && mouseAngle < start + angles[ix];
fill(red(colors[ix]), green(colors[ix]), blue(colors[ix]), hover ? 255 : 127);
arc(centerX, centerY, radius, radius, start, start + angles[ix]);
start += angles[ix];
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.js"></script>
相关文章