首页 > 解决方案 > 如何从此画布中获取每个圆的坐标

问题描述

我需要创建一个模式,其中 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>

标签: javascriptcsscanvashtml5-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

参考:检测用户是否在圆圈内点击


推荐阅读