SVG and JavaScript [#2]


Some SVG drawing using the JavaScript Math object.

Using the SVG line command, we can draw lines from one point to another.

The relevant parts are the starting points (x1 & y1) and ending points (x2 & y2).

In this example we start all lines at 0,0 (x1,y1).

By changing the x2 and y2 values, we stop the red lines on the blue circle (radius of 500).

Ahh. How to determine the x2 and y2 values of the line command?

Here is where we use some trigonometry, and the built-in JavaScript object Math, which contains several math functions and constants.


We know that the length of the line is always 500 (the circle radius).

To find an X value we take the sine of the angle, and multiply it by 500.

The Y value is found by taking the cosine of the angle, and multiplying it by 500.


So our JavaScript can loop through angles, finding the sine and cosine of each, then multiplying the number by 500 to get the X and Y coordinates.

However, JavaScript uses radians, not degrees for its trig functions, so first we have to convert our degrees to radians:

Multiply by 0.017453293 (2π / 360 OR π / 180)

Here's the code that produces this image:

<script>
<![CDATA[
var Angle;
var X2;
var Y2;
var D2R= (Math.PI / 180);
/* convert degrees to radians */
for (Angle=7.5; Angle <= 82.5; Angle += 7.5)
{
var Rx2=Angle*D2R;
var Ry2=Angle*D2R;
X2 = Math.sin(Rx2) * 500;
Y2 = Math.cos(Ry2) * 500;
document.write('<line x1=0 y1=0 x2=' + X2 + ' y2=' + Y2 + ' stroke="red" stroke-width="1"/>
');
}
]]>
</script>

With a few lines of JavaScript we drew 11 lines of specific length and angle. No guessing. I like that.