【问题标题】:How do I create a canvas circle with a triangle inside it?如何创建一个里面有一个三角形的画布圆圈?
【发布时间】:2018-09-27 19:24:12
【问题描述】:

我想创建一个带圆圈的画布,圆圈内应该是一个三角形。我知道如何画一个简单的圆(下图),但是如何放入三角形呢?

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.beginPath();
context.arc(75,100,55,0,2 * Math.PI);
context.stroke();

【问题讨论】:

    标签: javascript canvas


    【解决方案1】:

    在调用stroke之前添加这些行

    context.moveTo(75,75);
    context.lineTo(100, 100);
    context.lineTo(25,150);
    context.lineTo(75,75);
    

    它有点出乎意料,但你明白了。

    【讨论】:

      【解决方案2】:

      为了在圆内绘制三角形,您需要计算顶点的位置。假设你的三角形是等边的,顶点之间的角度是 120 度或 2*Math.PI/3:

      var canvas = document.getElementById("myCanvas");
      var context = canvas.getContext("2d");
      
      let cw = canvas.width = 300;// the width of the canvas
      let ch = canvas.height = 300;// the height of the canvas
      
      let c={// the circle: coords of the center and the radius
        x:75,y:100,r:55
      }
      
      let angle = (2*Math.PI)/3;// the angle between vertices
      
      points = [];// the vertices array
         
      
      for(let i = 0; i < 3; i++){
        let o = {}
        o.x = c.x + c.r*Math.cos(i*angle);
        o.y = c.y + c.r*Math.sin(i*angle);
        points.push(o); 
      }
      
      // draw the circle
      context.beginPath();
      context.arc(c.x,c.y,c.r,0,2 * Math.PI);
      context.stroke();
      
      
      // draw the triangle
      context.beginPath();
      context.moveTo(points[0].x,points[0].y);
      for(let i = 1; i < points.length; i++){
        context.lineTo(points[i].x,points[i].y);
      }
      context.closePath();
      context.stroke();
      canvas{border:1px solid}
      &lt;canvas id="myCanvas"&gt;&lt;/canvas&gt;

      【讨论】:

      • @pordix 是的,我想,但我需要更多详细信息。圆圈应该围绕什么旋转。请再问一个包含所有细节的问题。我很乐意提供帮助。
      猜你喜欢
      • 2020-06-14
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 2019-03-03
      • 2014-01-01
      • 2012-11-12
      • 1970-01-01
      相关资源
      最近更新 更多