How to draw the bottom half of a circle in canvas

I am trying to draw the bottom half of the circle using the appropriate functions x = cos (theta), y = sin (theta). If I repeat the theta from Math.PI to 2 * Math.PI, I seem to get the top half of the circle:

enter image description here

What am I doing wrong in this piece of code:

window.onload = function() { var canvas = document.getElementById('circle-canvas'); if (canvas && canvas.getContext) { var context = canvas.getContext('2d'); if (context) { context.strokeStyle = "#369"; context.lineWidth = 4; j = canvas.width / 2; k = canvas.height / 2; r = canvas.width / 4; function computeX(theta, r, j, k){ return r * Math.cos(theta) + j; } function computeY(theta, r, j, k){ return r * Math.sin(theta) + k; } start = Math.PI; context.lineTo(computeX(start, r, j, k), computeY(start, r, j, k)); for(var theta = start; theta <= (2*Math.PI); theta += .1) { x = computeX(theta, r, j, k); y = computeY(theta, r, j, k), context.lineTo(x, y); } context.stroke(); context.closePath(); } } } 

EDIT: I know about arc function. I need to implement the arc in this way, because it will be used as part of a more serious problem, when I need to calculate each individual point of the arc.

+4
source share
5 answers

Just put a - before r

 y = computeY(theta, -r, j, k), 

Tested and working

+3
source

There is an arc function.

 var canvas = document.getElementById("circle-canvas"); var context = canvas.getContext("2d"); var centerX = canvas.width / 2; var centerY = canvas.height / 4; var radius = canvas.width / 4; // I think these values are the angles for the bottom half - otherwise use other values var startingAngle = Math.PI; var endingAngle = 0; var counterclockwise = true; context.arc(centerX, centerY, radius, startingAngle, endingAngle, counterclockwise); context.lineWidth = 4; context.strokeStyle = "#369"; context.stroke(); 
+8
source

You need to change the start to 0 , and the end point to Math.Pi

Not quite sure why, but it seems that the canvas is going clockwise and not counterclockwise.

See an example here: http://jsfiddle.net/kvAzb/1/

The above solution works, but this is not the right solution. New solution below:

EDIT

Yeah, Roger's comment explains it. The canvas coordinates start at 0,0 in the upper left corner, and not in the lower left corner. So you need to flip your computeY function.

function computeY(theta, r, j, k){ return r * Math.sin(theta) + k; }

changes to

function computeY(theta, r, j, k){ return canvas.height - (r * Math.sin(theta) + k); }

+4
source

There is a function that suits you, arc .

 var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); context.arc(256, 128, 128, Math.PI, 0, true); context.stroke(); 

http://jsfiddle.net/9mAq5/

+2
source

guess quickly, try changing the sign (if you use positive relative coordinates, try using negatives)

0
source

Source: https://habr.com/ru/post/1383661/


All Articles