Reputation: 21
I want to create a canvas with a circle, and inside the circle should be a triangle. I know how to draw a simple circle (below), but how do I put in the triangle?
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.beginPath();
context.arc(75,100,55,0,2 * Math.PI);
context.stroke();
Upvotes: 1
Views: 1100
Reputation: 33024
In order to draw a triangle inside a circle you need to calculate the positions of the vertices. Supposing that your triangle is equilateral the angle between vertices is 120degs or 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>
Upvotes: 0
Reputation: 399
Add these lines before calling stroke
context.moveTo(75,75);
context.lineTo(100, 100);
context.lineTo(25,150);
context.lineTo(75,75);
It is coming out of the cirle a little bit, but you get the idea.
Upvotes: 1