Reputation: 174
I'm new to Canvas and I have no idea how to figure out where is the beginning or the end of a curve (well, arc). I am trying to draw an ice cream cone, it goes something like this:
<canvas id="5" width="280" height="280"></canvas>
<script>
var ctx = document.getElementById("5").getContext("2d");
var radio = 100;
ctx.beginPath();
ctx.arc(ctx.canvas.width/2, 20, radio, 0.7*pi, 0.3*pi, true);
ctx.lineTo(ctx.canvas.width/2, ctx.canvas.height-20);
ctx.lineJoin = "round";
ctx.lineTo(ctx.canvas.width/2, ctx.canvas.height-20);
// missing line
ctx.stroke();
ctx.closePath();
<script>
How can I draw a line from the current point to the beginning of the arc?
Upvotes: 0
Views: 67
Reputation:
To know where the end-points of an arc is take a look at this diagram:
As you can see the angle system always start with 0 radians pointing right (provided no rotation is already applied). 2 x PI is one full circle.
So for an arc it starts for example 0.5 x PI would be straight down while 1.5 x PI is straight up.
So for example if your absolute angles where: startAngle = 1.75 radians (incl. PI) and endAngle = 5.65 your arc would look like this (the line is something I added to show start angle but you can also see that you can create an attached line simply by using moveTo ahead of drawing the arc - see demo for details):
arc
has an optional parameter if your start angle is larger than end angle (ie. you want to draw the opposite way) which allows you to draw counter-clock-wise.
ctx.arc(cx, cy, cx, startAngle, endAngle, ccw);
Here is a simple toy where you can play around with the angle sliders to see where the arc's end-points ends up. It also deals with start angle being larger than end angle.
If I put in a closePath()
at the end the path would close my first point with the last point and in this case you could get a pie:
Upvotes: 1
Reputation: 105015
You can close your cone by putting ctx.closePath before ctx.stroke
ctx.beginPath();
ctx.arc(ctx.canvas.width/2, 20, radio, 0.7*pi, 0.3*pi, true);
ctx.lineTo(ctx.canvas.width/2, ctx.canvas.height-20);
ctx.lineJoin = "round";
ctx.lineTo(ctx.canvas.width/2, ctx.canvas.height-20);
ctx.closePath();
ctx.stroke();
If you want to find the XY at any point on an arc, you can do it like this:
function calcXYonArc(centerX,centerY,radius,radianAngle){
var x=centerX+radius*Math.cos(radianAngle);
var y=centerY+radius*Math.sin(radianAngle);
return({x:x,y:y});
}
// used like this:
var xy=calcXYonArc(canvas.width/2,20,radio,.7*pi);
ctx.fillStyle="red";
ctx.fillRect(xy.x-2,xy.y-2,4,4);
Upvotes: 0