javascript - 如何从此画布中获取每个圆的坐标
问题描述
我需要创建一个模式,其中 5 个圆圈由线连接到中间的主圆圈。所以我通过以某个角度旋转来动态创建。现在我需要每个圆圈的 x 和 y 轴坐标来捕获每个圆圈上的点击事件。
请帮助我如何找出每个圆的坐标?
var canvas, ctx;
function createCanvasPainting() {
canvas = document.getElementById('myCanvas');
if (!canvas || !canvas.getContext) {
return false;
}
canvas.width = 600;
canvas.height = 600;
ctx = canvas.getContext('2d');
ctx.strokeStyle = '#B8D9FE';
ctx.fillStyle = '#B8D9FE';
ctx.translate(300, 250);
ctx.arc(0, 0, 50, 0, Math.PI * 2); //center circle
ctx.stroke();
ctx.fill();
drawChildCircles(5);
fillTextMultiLine('Test Data', 0, 0);
drawTextInsideCircles(5);
}
function drawTextInsideCircles(n) {
let ang_unit = Math.PI * 2 / n;
ctx.save();
for (var i = 0; i < n; i++) {
ctx.rotate(ang_unit);
//ctx.moveTo(0,0);
fillTextMultiLine('Test Data', 200, 0);
ctx.strokeStyle = '#B8D9FE';
ctx.fillStyle = '#B8D9FE';
}
ctx.restore();
}
function drawChildCircles(n) {
let ang_unit = Math.PI * 2 / n;
ctx.save();
for (var i = 0; i < n; ++i) {
ctx.rotate(ang_unit);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(100,0);
ctx.arc(200, 0, 40, 0, Math.PI * 2);
let newW = ctx.fill();
ctx.stroke();
}
ctx.restore();
}
function fillTextMultiLine(text, x, y) {
ctx.font = 'bold 13pt Calibri';
ctx.textAlign = 'center';
ctx.fillStyle = "#FFFFFF";
// Defining the `textBaseline`…
ctx.textBaseline = "middle";
var lineHeight = ctx.measureText("M").width * 1.2;
var lines = text.split("\n");
for (var i = 0; i < lines.length; ++i) {
// console.log(lines);
if (lines.length > 1) {
if (i == 0) {
y -= lineHeight;
} else {
y += lineHeight;
}
}
ctx.fillText(lines[i], x, y);
}
}
createCanvasPainting();
<canvas id="myCanvas"></canvas>
解决方案
这里的问题是您正在旋转画布矩阵,而您的圆圈不知道它们的绝对位置。
你为什么不使用一些简单的三角函数来确定你的圆心和连接线的终点?
function lineToAngle(ctx, x1, y1, length, angle) {
angle *= Math.PI / 180;
var x2 = x1 + length * Math.cos(angle),
y2 = y1 + length * Math.sin(angle);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
return {x: x2, y: y2};
}
参考:画布旋转后查找坐标
之后,给定圆的 xy 中心,计算坐标是否在圆内,您可以应用以下公式:
Math.sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)) < r
参考:检测用户是否在圆圈内点击
推荐阅读
- node.js - 使用 brotli 压缩和解压 utf8 字符串
- matlab - 如何使用 MATLAB 获取图形的两个单个节点之间的所有现有最短路径
- elasticsearch - 在弹性搜索中使用 GET API 进行搜索查询
- swift - URL 错误:在展开可选值时意外发现 nil:文件
- python - 在单独的控制台窗口中启动应用程序(需要用户交互)
- python-3.x - 与 timedistributedlayer 相关的 tf2.0 内存泄漏(渴望)
- r - 每组ggridges颜色渐变
- android - 找不到类 BadgeDrawable。如何在 Android 中使用 Material Design BadgeDrawable
- cordova - 覆盖 CapacitorWebView 上的 shouldOverrideUrlLoading 和 onPageFinished
- ios - 在不中断背景媒体播放的情况下录制音频