SVG and JavaScript [#1]


Using JavaScript it is possible to create complex patterns and shapes easier and with less coding.

Remember that when using JavaScript inside an svg block, we must use the following syntax:

<script>
<![CDATA[
.
.
.
]]>
</script>

This is so any < and > angle brackets are interpreted correctly.

In this case we use a simple loop, to first create the red lines.

Then in the same loop, we change the beginning x1 starting point and the stroke color.

var j=250; /* x2 */
for (a = 60;a <= 450;a += 10)
/* y2 */
{
  document.write('<line x1=0 y1=250' + ' x2=' + j + ' y2=' + a + ' stroke="red" stroke-width="1"/>');
  document.write('<line x1=500 y1=250' + ' x2=' + j + ' y2=' + a + ' stroke="blue" stroke-width="1"/>');
}

The eagle-eyed viewer may notice that there are 20 red lines and 20 blue lines. Typically that would require 40 lines of code to generate the image.

Using a JavaScript loop, we have accomplished this in about 4 lines of code.

 

All done.