Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG JavaScript "pie wedge" generator

Tags:

javascript

svg

I'm trying to create a "pie wedge". And I'm bad at it. It's been a LONG time since I took trig. I have looked at lots of examples, and have this code generator worked out in JS:

var startPointX = 200;
var startPointY = 200;
var startAngle = 180;
var endAngle = 210;
var x1 = startPointX + 180*Math.cos(Math.PI*startAngle/180); 
var y1 = startPointY + 180*Math.sin(Math.PI*startAngle/180); 

var x2 = startPointX + 180*Math.cos(Math.PI*endAngle/180);
var y2 = startPointY + 180*Math.sin(Math.PI*endAngle/180);
console.log("M200,200 L" + x1 + "," + y1 + " A180,180 0 0,1 " + x2 + "," + y2 + " z");

It works great!

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <path d="M200,200 L20,200 A180,180 0 0,1 44.1,110 z" fill="red" stroke="none" stroke-width="0" />
</svg>

But, what I need to do is change the radius of the "wedge" that's generated. I can't seem to figure out which parameters correspond, or how I would go about modifying my equations to compensate. Replacing all the "180"s gives me some freaky results.

like image 462
Randy Hall Avatar asked Jul 16 '26 01:07

Randy Hall


1 Answers

The first two values in the arc (after the A) are the starting coordinates of the arc, so should equal x1, y1. Try:

var startPointX = 200;
var startPointY = 200;
var startAngle = 180;
var endAngle = 210;
var radius = 100;

var x1 = startPointX + radius * Math.cos(Math.PI * startAngle/180); 
var y1 = startPointY + radius * Math.sin(Math.PI * startAngle/180);     
var x2 = startPointX + radius * Math.cos(Math.PI * endAngle/180);
var y2 = startPointY + radius * Math.sin(Math.PI * endAngle/180);

console.log("M200,200 L" + x1 + "," + y1 + " A" + radius + "," + radius + " 0 0,1 " + x2 + "," + y2 + " z");
like image 174
Peter Collingridge Avatar answered Jul 17 '26 13:07

Peter Collingridge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!