我想创建一个带圆圈的画布,并且圆圈内应该是一个三角形。我知道如何绘制一个简单的圆(如下),但是如何放入三角形?
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.beginPath();
context.arc(75,100,55,0,2 * Math.PI);
context.stroke();
答案 0 :(得分:1)
在致电stroke
context.moveTo(75,75);
context.lineTo(100, 100);
context.lineTo(25,150);
context.lineTo(75,75);
它有点圆,但是你知道了。
答案 1 :(得分:0)
要在圆内绘制三角形,需要计算顶点的位置。假设您的三角形是等边的,则顶点之间的角度为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}
<canvas id="myCanvas"></canvas>