3 JavaScript routines to dynamically generate Scalable Vector Graphics
4 using a mathematical xy-coordinate system (y increases upwards) and
5 very intuitive JavaScript commands (no programming experience required).
6 ASCIIsvg.js is good for learning math and illustrating online math texts.
7 Works with Internet Explorer+Adobe SVGviewer and SVG enabled Mozilla/Firefox.
9 Ver 1.2.7 Oct 13, 2005 (c) Peter Jipsen http://www.chapman.edu/~jipsen
10 Latest version at http://www.chapman.edu/~jipsen/svg/ASCIIsvg.js
11 If you use it on a webpage, please send the URL to jipsen@chapman.edu
13 This program is free software; you can redistribute it and/or modify
14 it under the terms of the GNU General Public License as published by
15 the Free Software Foundation; either version 2 of the License, or (at
16 your option) any later version.
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 General Public License (at http://www.gnu.org/copyleft/gpl.html)
24 var checkIfSVGavailable = true;
25 var notifyIfNoSVG = true;
26 var alertIfNoSVG = false;
27 var xunitlength = 20; // pixels
28 var yunitlength = 20; // pixels
29 var origin = [0,0]; // in pixels (default is bottom left corner)
30 var defaultwidth = 300; defaultheight = 200; defaultborder = 0;
31 var border = defaultborder;
32 var strokewidth, strokedasharray, stroke, fill;
33 var fontstyle, fontfamily, fontsize, fontweight, fontstroke, fontfill;
34 var markerstrokewidth = "1";
35 var markerstroke = "black";
36 var markerfill = "yellow";
38 var arrowfill = stroke;
41 var axesstroke = "black";
42 var gridstroke = "grey";
43 var pointerpos = null;
44 var coordinates = null;
49 var aboveleft = "aboveleft";
50 var aboveright = "aboveright";
51 var belowleft = "belowleft";
52 var belowright = "belowright";
53 var cpi = "\u03C0", ctheta = "\u03B8";
54 var pi = Math.PI, ln = Math.log, e = Math.E;
55 var arcsin = Math.asin, arccos = Math.acos, arctan = Math.atan;
56 var sec = function(x) { return 1/Math.cos(x) };
57 var csc = function(x) { return 1/Math.sin(x) };
58 var cot = function(x) { return 1/Math.tan(x) };
59 var xmin, xmax, ymin, ymax, xscl, yscl,
60 xgrid, ygrid, xtick, ytick, initialized;
61 var isIE = document.createElementNS==null;
62 var picture, svgpicture, doc, width, height, a, b, c, d, i, n, p, t, x, y;
63 var arcsec = function(x) { return arccos(1/x) };
64 var arccsc = function(x) { return arcsin(1/x) };
65 var arccot = function(x) { return arctan(1/x) };
66 var sinh = function(x) { return (Math.exp(x)-Math.exp(-x))/2 };
67 var cosh = function(x) { return (Math.exp(x)+Math.exp(-x))/2 };
69 function(x) { return (Math.exp(x)-Math.exp(-x))/(Math.exp(x)+Math.exp(-x)) };
70 var sech = function(x) { return 1/cosh(x) };
71 var csch = function(x) { return 1/sinh(x) };
72 var coth = function(x) { return 1/tanh(x) };
73 var arcsinh = function(x) { return ln(x+Math.sqrt(x*x+1)) };
74 var arccosh = function(x) { return ln(x+Math.sqrt(x*x-1)) };
75 var arctanh = function(x) { return ln((1+x)/(1-x))/2 };
76 var sech = function(x) { return 1/cosh(x) };
77 var csch = function(x) { return 1/sinh(x) };
78 var coth = function(x) { return 1/tanh(x) };
79 var arcsech = function(x) { return arccosh(1/x) };
80 var arccsch = function(x) { return arcsinh(1/x) };
81 var arccoth = function(x) { return arctanh(1/x) };
82 var sign = function(x) { return (x==0?0:(x<0?-1:1)) };
84 function factorial(x,n) {
86 for (var i=x-n; i>0; i-=n) x*=i;
87 return (x<0?NaN:(x==0?1:x));
92 for (var i=0; i<k; i++) res*=(x-i)/(k-i);
98 return Math.floor(x*Math.pow(10,n))/Math.pow(10,n);
101 function ran(a,b,n) {
103 return chop((b+Math.pow(10,-n)-a)*Math.random()+a,n);
106 function myCreateElementXHTML(t) {
107 if (isIE) return document.createElement(t);
108 else return document.createElementNS("http://www.w3.org/1999/xhtml",t);
111 function isSVGavailable() {
112 var ua = navigator.userAgent;
113 if (ua.match("AppleWebKit")) {
116 if (navigator.appName.slice(0,5)=="Opera") {
119 var nd = myCreateElementXHTML("center");
120 nd.appendChild(document.createTextNode("To view the "));
121 var an = myCreateElementXHTML("a");
122 an.appendChild(document.createTextNode("ASCIIsvg"));
123 an.setAttribute("href","http://www.chapman.edu/~jipsen/asciisvg.html");
125 nd.appendChild(document.createTextNode(" images use Internet Explorer 6+"));
126 an = myCreateElementXHTML("a");
127 an.appendChild(document.createTextNode("Adobe SVGviewer 3.02"));
128 an.setAttribute("href","http://www.adobe.com/svg");
130 nd.appendChild(document.createTextNode(" or "));
131 an = myCreateElementXHTML("a");
132 an.appendChild(document.createTextNode("SVG enabled Mozilla/Firefox"));
133 an.setAttribute("href",
134 "http://www.chapman.edu/~jipsen/svg/svgenabledmozillafirefox.html");
136 if (navigator.appName.slice(0,8)=="Netscape")
137 if (window['SVGElement']) return null;
139 else if (navigator.appName.slice(0,9)=="Microsoft")
141 var oSVG=eval("new ActiveXObject('Adobe.SVGCtl.3');");
150 function less(x,y) { return x < y } // used for scripts in XML files
151 // since IE does not handle CDATA well
152 function setText(st,id) {
153 var node = document.getElementById(id);
155 if (node.childNodes.length!=0) node.childNodes[0].nodeValue = st;
156 else node.appendChild(document.createTextNode(st));
159 function myCreateElementSVG(t) {
160 if (isIE) return doc.createElement(t);
161 else return doc.createElementNS("http://www.w3.org/2000/svg",t);
165 return (doc.getElementById("pointerpos").getAttribute("cx")-origin[0])/xunitlength;
169 return (height-origin[1]-doc.getElementById("pointerpos").getAttribute("cy"))/yunitlength;
172 function mousemove_listener(evt) {
173 if (svgpicture.getAttribute("xbase")!=null)
174 pointerpos.cx.baseVal.value = evt.clientX-svgpicture.getAttribute("xbase");
175 if (svgpicture.getAttribute("ybase")!=null)
176 pointerpos.cy.baseVal.value = evt.clientY-svgpicture.getAttribute("ybase");
179 function top_listener(evt) {
180 svgpicture.setAttribute("ybase",evt.clientY);
183 function bottom_listener(evt) {
184 svgpicture.setAttribute("ybase",evt.clientY-height+1);
187 function left_listener(evt) {
188 svgpicture.setAttribute("xbase",evt.clientX);
191 function right_listener(evt) {
192 svgpicture.setAttribute("xbase",evt.clientX-width+1);
195 function drawPictures() { // main routine; called after webpage has loaded
196 var src, id, dsvg, onmov, nd, node, ht, index;
197 var pictures = document.getElementsByTagName("textarea");
198 for (index = 0; index<pictures.length; index++)
199 if (pictures[index].className=="ASCIIsvg"){
200 pictures[index].style.display="none"; // hide the textarea
202 pictures = document.getElementsByTagName("embed");
203 var len = pictures.length;
204 if (checkIfSVGavailable) {
205 nd = isSVGavailable();
206 if (nd != null && notifyIfNoSVG && len>0)
208 alert("To view the SVG pictures in Internet Explorer\n\
209 download the free Adobe SVGviewer from www.adobe.com/svg or\n\
210 use Firefox 1.5 preview (called Deerpark)");
212 var ASbody = document.getElementsByTagName("body")[0];
213 ASbody.insertBefore(nd,ASbody.childNodes[0]);
217 for (index = 0; index < len; index++) {
218 xmin = null; xmax = null; ymin = null; ymax = null;
219 xscl = null; xgrid = null; yscl = null; ygrid = null;
221 picture = (isIE ? pictures[index] : pictures[0]);
222 src = picture.getAttribute("script");
223 if (src==null) src = "";
224 ht = picture.getAttribute("height");
225 if (ht==null) ht ="";
226 if (ht!="") defaultborder = 25;
227 if (ht=="" || src=="")
228 if (document.getElementById("picture"+(index+1)+"input")==null) {
229 if (isIE && src.indexOf("nobutton()")==-1)
230 picture.parentNode.insertBefore(myCreateElementXHTML("br"),picture);
231 node = myCreateElementXHTML("textarea");
232 node.setAttribute("rows","10");
233 node.setAttribute("cols","60");
234 // node.setAttribute("style","display:block");
235 if (isIE) src = src.replace(/([^\r])\n/g,"$1\r").slice(1);
236 node.appendChild(document.createTextNode(src));
237 if (src.indexOf("showcode()")==-1) node.style.display = "none";
238 node.setAttribute("id","picture"+(index+1)+"input");
239 picture.parentNode.insertBefore(node,picture);
241 if (src.indexOf("nobutton()")==-1) {
242 picture.parentNode.insertBefore(myCreateElementXHTML("br"),picture);
244 node = myCreateElementXHTML("button");
245 if (isIE) node.onclick = function() { showHideCode(this) };
246 else node.setAttribute("onclick","showHideCode(this)");
247 node.appendChild(document.createTextNode("Show/Hide"));
248 picture.parentNode.insertBefore(node,picture);
250 node = myCreateElementXHTML("button");
251 if (isIE) node.onclick = ASfn[index];
252 else node.setAttribute("onclick","updatePicture("+index+")");
253 node.appendChild(document.createTextNode("Update"));
254 if (src.indexOf("showCode()")==-1) node.style.display = "none";
255 picture.parentNode.insertBefore(node,picture);
257 /* node = myCreateElementXHTML("span");
258 // node.setAttribute("id","AScoord"+index);
259 node.appendChild(document.createTextNode("(x,y)"));
260 picture.parentNode.insertBefore(node,picture);
262 picture.parentNode.insertBefore(myCreateElementXHTML("br"),picture);
264 if (isIE) picture.onmousemove = ASupdateCoords[index];
265 else picture.setAttribute("onmousemove","updateCoords"+index+"()");
266 } else src = document.getElementById("picture"+(index+1)+"input").value;
267 src = src.replace(/plot\(\x20*([^\"f\[][^\n\r]+?)\,/g,"plot\(\"$1\",");
268 src = src.replace(/plot\(\x20*([^\"f\[][^\n\r]+)\)/g,"plot(\"$1\")");
269 src = src.replace(/([0-9])([a-zA-Z])/g,"$1*$2");
270 src = src.replace(/\)([\(0-9a-zA-Z])/g,"\)*$1");
271 // eval(src.replace(/\s\s/g,";")); //for XML version
272 id = picture.getAttribute("id");
273 dsvg = picture.getAttribute("src");
274 onmov = picture.getAttribute("onmousemove");
275 if (id == null || id == "") {
276 id = "picture"+(index+1);
277 picture.setAttribute("id",id);
280 with (Math) eval(src);
281 } catch(err) {alert(err+"\n"+src)}
282 if (isIE) src = src.replace(/([^\r])\n/g,"$1\r");
283 setText("<embed width=\""+width+"\" height=\""+height+"\" src=\""+
284 dsvg+"\" "+(onmov!=null?"onmousemove=\""+onmov+"\"":"")+
285 (isIE?"\r":"\n")+"script=\'"+src+"\'>",id+"script");
286 // setText(src.replace(/\s\s/g,"\r"),id+"script"); //for XML version
291 function switchTo(id) {
293 picture = document.getElementById(id);
294 width = picture.getAttribute("width")-0;
295 height = picture.getAttribute("height")-0;
296 strokewidth = "1" // pixel
297 stroke = "black"; // default line color
298 fill = "none"; // default fill color
300 if ((picture.nodeName == "EMBED" || picture.nodeName == "embed") && isIE) {
301 svgpicture = picture.getSVGDocument().getElementById("root");
302 doc = picture.getSVGDocument();
304 picture.setAttribute("onmousemove","updateCoords"+(id.slice(id.length-1)-1)+"()");
305 //alert(picture.getAttribute("onmousemove")+"***");
306 svgpicture = picture;
309 xunitlength = svgpicture.getAttribute("xunitlength")-0;
310 yunitlength = svgpicture.getAttribute("yunitlength")-0;
311 xmin = svgpicture.getAttribute("xmin")-0;
312 xmax = svgpicture.getAttribute("xmax")-0;
313 ymin = svgpicture.getAttribute("ymin")-0;
314 ymax = svgpicture.getAttribute("ymax")-0;
315 origin = [svgpicture.getAttribute("ox")-0,svgpicture.getAttribute("oy")-0];
318 function updatePicture(obj) {
320 var src = document.getElementById((typeof obj=="string"?
321 obj:"picture"+(obj+1)+"input")).value;
322 xmin = null; xmax = null; ymin = null; ymax = null;
323 xscl = null; xgrid = null; yscl = null; ygrid = null;
325 switchTo((typeof obj=="string"?obj.slice(0,8):"picture"+(obj+1)));
326 src = src.replace(/plot\(\x20*([^\"f\[][^\n\r]+?)\,/g,"plot\(\"$1\",");
327 src = src.replace(/plot\(\x20*([^\"f\[][^\n\r]+)\)/g,"plot(\"$1\")");
328 src = src.replace(/([0-9])([a-zA-Z])/g,"$1*$2");
329 src = src.replace(/\)([\(0-9a-zA-Z])/g,"\)*$1");
332 with (Math) eval(src);
333 } catch(err) {alert(err+"\n"+src)}
336 function showHideCode(obj) {
337 var node = obj.nextSibling;
338 while (node != null && node.nodeName != "BUTTON" &&
339 node.nodeName != "button") node = node.nextSibling;
340 if (node.style.display == "none") node.style.display = "";
341 else node.style.display = "none";
342 while (node != null && node.nodeName != "TEXTAREA" &&
343 node.nodeName != "textarea") node = node.previousSibling;
344 if (node.style.display == "none") node.style.display = "";
345 else node.style.display = "none";
346 // updatePicture(node.getAttribute("id"));
349 function hideCode() { //do nothing
352 function showcode() { //do nothing
355 function nobutton() { //do nothing
358 function setBorder(x) { border = x }
360 function initPicture(x_min,x_max,y_min,y_max) {
362 strokewidth = "1"; // pixel
363 strokedasharray = null;
364 stroke = "black"; // default line color
365 fill = "none"; // default fill color
366 fontstyle = "italic"; // default shape for text labels
367 fontfamily = "times"; // default font
368 fontsize = "16"; // default size
369 fontweight = "normal";
370 fontstroke = "none"; // default font outline color
371 fontfill = "none"; // default font color
374 if (x_min!=null) xmin = x_min;
375 if (x_max!=null) xmax = x_max;
376 if (y_min!=null) ymin = y_min;
377 if (y_max!=null) ymax = y_max;
378 if (xmin==null) xmin = -5;
379 if (xmax==null) xmax = 5;
380 if (typeof xmin != "number" || typeof xmax != "number" || xmin >= xmax)
381 alert("Picture requires at least two numbers: xmin < xmax");
382 else if (y_max != null && (typeof y_min != "number" ||
383 typeof y_max != "number" || y_min >= y_max))
384 alert("initPicture(xmin,xmax,ymin,ymax) requires numbers ymin < ymax");
386 if (width==null) width = picture.getAttribute("width");
387 else picture.setAttribute("width",width);
388 if (width==null || width=="") width=defaultwidth;
389 if (height==null) height = picture.getAttribute("height");
390 else picture.setAttribute("height",height);
391 if (height==null || height=="") height=defaultheight;
392 xunitlength = (width-2*border)/(xmax-xmin);
393 yunitlength = xunitlength;
394 //alert(xmin+" "+xmax+" "+ymin+" "+ymax)
396 origin = [-xmin*xunitlength+border,height/2];
397 ymin = -(height-2*border)/(2*yunitlength);
400 if (ymax!=null) yunitlength = (height-2*border)/(ymax-ymin);
401 else ymax = (height-2*border)/yunitlength + ymin;
402 origin = [-xmin*xunitlength+border,-ymin*yunitlength+border];
404 // if (true ||picture.nodeName == "EMBED" || picture.nodeName == "embed") {
406 svgpicture = picture.getSVGDocument().getElementById("root");
407 while (svgpicture.childNodes.length()>5)
408 svgpicture.removeChild(svgpicture.lastChild);
409 svgpicture.setAttribute("width",width);
410 svgpicture.setAttribute("height",height);
411 doc = picture.getSVGDocument();
413 var qnode = document.createElementNS("http://www.w3.org/2000/svg","svg");
414 qnode.setAttribute("id",picture.getAttribute("id"));
415 qnode.setAttribute("style","display:inline");
416 qnode.setAttribute("width",picture.getAttribute("width"));
417 qnode.setAttribute("height",picture.getAttribute("height"));
418 if (picture.parentNode!=null)
419 picture.parentNode.replaceChild(qnode,picture);
421 svgpicture.parentNode.replaceChild(qnode,svgpicture);
424 pointerpos = doc.getElementById("pointerpos");
425 if (pointerpos==null) {
426 pointerpos = myCreateElementSVG("circle");
427 pointerpos.setAttribute("id","pointerpos");
428 pointerpos.setAttribute("cx",0);
429 pointerpos.setAttribute("cy",0);
430 pointerpos.setAttribute("r",0.5);
431 pointerpos.setAttribute("fill","red");
432 svgpicture.appendChild(pointerpos);
436 // svgpicture = picture;
439 svgpicture.setAttribute("xunitlength",xunitlength);
440 svgpicture.setAttribute("yunitlength",yunitlength);
441 svgpicture.setAttribute("xmin",xmin);
442 svgpicture.setAttribute("xmax",xmax);
443 svgpicture.setAttribute("ymin",ymin);
444 svgpicture.setAttribute("ymax",ymax);
445 svgpicture.setAttribute("ox",origin[0]);
446 svgpicture.setAttribute("oy",origin[1]);
447 var node = myCreateElementSVG("rect");
448 node.setAttribute("x","0");
449 node.setAttribute("y","0");
450 node.setAttribute("width",width);
451 node.setAttribute("height",height);
452 node.setAttribute("style","stroke-width:1;fill:white");
453 svgpicture.appendChild(node);
454 if (!isIE && picture.getAttribute("onmousemove")!=null) {
455 svgpicture.addEventListener("mousemove", mousemove_listener, true);
456 var st = picture.getAttribute("onmousemove");
457 svgpicture.addEventListener("mousemove", eval(st.slice(0,st.indexOf("("))), true);
458 node = myCreateElementSVG("polyline");
459 node.setAttribute("points","0,0 "+width+",0");
460 node.setAttribute("style","stroke:white; stroke-width:3");
461 node.addEventListener("mousemove", top_listener, true);
462 svgpicture.appendChild(node);
463 node = myCreateElementSVG("polyline");
464 node.setAttribute("points","0,"+height+" "+width+","+height);
465 node.setAttribute("style","stroke:white; stroke-width:3");
466 node.addEventListener("mousemove", bottom_listener, true);
467 svgpicture.appendChild(node);
468 node = myCreateElementSVG("polyline");
469 node.setAttribute("points","0,0 0,"+height);
470 node.setAttribute("style","stroke:white; stroke-width:3");
471 node.addEventListener("mousemove", left_listener, true);
472 svgpicture.appendChild(node);
473 node = myCreateElementSVG("polyline");
474 node.setAttribute("points",(width-1)+",0 "+(width-1)+","+height);
475 node.setAttribute("style","stroke:white; stroke-width:3");
476 node.addEventListener("mousemove", right_listener, true);
477 svgpicture.appendChild(node);
479 border = defaultborder;
484 function line(p,q,id) { // segment connecting points p,q (coordinates in units)
486 if (id!=null) node = doc.getElementById(id);
488 node = myCreateElementSVG("path");
489 node.setAttribute("id", id);
490 svgpicture.appendChild(node);
492 node.setAttribute("d","M"+(p[0]*xunitlength+origin[0])+","+
493 (height-p[1]*yunitlength-origin[1])+" "+
494 (q[0]*xunitlength+origin[0])+","+(height-q[1]*yunitlength-origin[1]));
495 node.setAttribute("stroke-width", strokewidth);
496 if (strokedasharray!=null)
497 node.setAttribute("stroke-dasharray", strokedasharray);
498 node.setAttribute("stroke", stroke);
499 node.setAttribute("fill", fill);
500 if (marker=="dot" || marker=="arrowdot") {
501 ASdot(p,4,markerstroke,markerfill);
502 if (marker=="arrowdot") arrowhead(p,q);
503 ASdot(q,4,markerstroke,markerfill);
504 } else if (marker=="arrow") arrowhead(p,q);
507 function path(plist,id,c) {
510 if (id!=null) node = doc.getElementById(id);
512 node = myCreateElementSVG("path");
513 node.setAttribute("id", id);
514 svgpicture.appendChild(node);
516 if (typeof plist == "string") st = plist;
519 st += (plist[0][0]*xunitlength+origin[0])+","+
520 (height-plist[0][1]*yunitlength-origin[1])+" "+c;
521 for (i=1; i<plist.length; i++)
522 st += (plist[i][0]*xunitlength+origin[0])+","+
523 (height-plist[i][1]*yunitlength-origin[1])+" ";
525 node.setAttribute("d", st);
526 node.setAttribute("stroke-width", strokewidth);
527 if (strokedasharray!=null)
528 node.setAttribute("stroke-dasharray", strokedasharray);
529 node.setAttribute("stroke", stroke);
530 node.setAttribute("fill", fill);
531 if (marker=="dot" || marker=="arrowdot")
532 for (i=0; i<plist.length; i++)
533 if (c!="C" && c!="T" || i!=1 && i!=2)
534 ASdot(plist[i],4,markerstroke,markerfill);
537 function curve(plist,id) {
541 function circle(center,radius,id) { // coordinates in units
543 if (id!=null) node = doc.getElementById(id);
545 node = myCreateElementSVG("circle");
546 node.setAttribute("id", id);
547 svgpicture.appendChild(node);
549 node.setAttribute("cx",center[0]*xunitlength+origin[0]);
550 node.setAttribute("cy",height-center[1]*yunitlength-origin[1]);
551 node.setAttribute("r",radius*xunitlength);
552 node.setAttribute("stroke-width", strokewidth);
553 node.setAttribute("stroke", stroke);
554 node.setAttribute("fill", fill);
557 function loop(p,d,id) {
558 // d is a direction vector e.g. [1,0] means loop starts in that direction
559 if (d==null) d=[1,0];
560 path([p,[p[0]+d[0],p[1]+d[1]],[p[0]-d[1],p[1]+d[0]],p],id,"C");
561 if (marker=="arrow" || marker=="arrowdot")
562 arrowhead([p[0]+Math.cos(1.4)*d[0]-Math.sin(1.4)*d[1],
563 p[1]+Math.sin(1.4)*d[0]+Math.cos(1.4)*d[1]],p);
566 function arc(start,end,radius,id) { // coordinates in units
568 //alert([fill, stroke, origin, xunitlength, yunitlength, height])
569 if (id!=null) node = doc.getElementById(id);
571 v=[end[0]-start[0],end[1]-start[1]];
572 radius = Math.sqrt(v[0]*v[0]+v[1]*v[1]);
575 node = myCreateElementSVG("path");
576 node.setAttribute("id", id);
577 svgpicture.appendChild(node);
579 node.setAttribute("d","M"+(start[0]*xunitlength+origin[0])+","+
580 (height-start[1]*yunitlength-origin[1])+" A"+radius*xunitlength+","+
581 radius*yunitlength+" 0 0,0 "+(end[0]*xunitlength+origin[0])+","+
582 (height-end[1]*yunitlength-origin[1]));
583 node.setAttribute("stroke-width", strokewidth);
584 node.setAttribute("stroke", stroke);
585 node.setAttribute("fill", fill);
586 if (marker=="arrow" || marker=="arrowdot") {
587 u = [(end[1]-start[1])/4,(start[0]-end[0])/4];
588 v = [(end[0]-start[0])/2,(end[1]-start[1])/2];
590 v = [start[0]+v[0]+u[0],start[1]+v[1]+u[1]];
591 } else v=[start[0],start[1]];
592 if (marker=="dot" || marker=="arrowdot") {
593 ASdot(start,4,markerstroke,markerfill);
594 if (marker=="arrowdot") arrowhead(v,end);
595 ASdot(end,4,markerstroke,markerfill);
596 } else if (marker=="arrow") arrowhead(v,end);
599 function ellipse(center,rx,ry,id) { // coordinates in units
601 if (id!=null) node = doc.getElementById(id);
603 node = myCreateElementSVG("ellipse");
604 node.setAttribute("id", id);
605 svgpicture.appendChild(node);
607 node.setAttribute("cx",center[0]*xunitlength+origin[0]);
608 node.setAttribute("cy",height-center[1]*yunitlength-origin[1]);
609 node.setAttribute("rx",rx*xunitlength);
610 node.setAttribute("ry",ry*yunitlength);
611 node.setAttribute("stroke-width", strokewidth);
612 node.setAttribute("stroke", stroke);
613 node.setAttribute("fill", fill);
616 function rect(p,q,id,rx,ry) { // opposite corners in units, rounded by radii
618 if (id!=null) node = doc.getElementById(id);
620 node = myCreateElementSVG("rect");
621 node.setAttribute("id", id);
622 svgpicture.appendChild(node);
624 node.setAttribute("x",p[0]*xunitlength+origin[0]);
625 node.setAttribute("y",height-q[1]*yunitlength-origin[1]);
626 node.setAttribute("width",(q[0]-p[0])*xunitlength);
627 node.setAttribute("height",(q[1]-p[1])*yunitlength);
628 if (rx!=null) node.setAttribute("rx",rx*xunitlength);
629 if (ry!=null) node.setAttribute("ry",ry*yunitlength);
630 node.setAttribute("stroke-width", strokewidth);
631 node.setAttribute("stroke", stroke);
632 node.setAttribute("fill", fill);
635 function text(p,st,pos,id,fontsty) {
636 var textanchor = "middle";
637 var dx = 0; var dy = fontsize/3;
639 if (pos.slice(0,5)=="above") dy = -fontsize/2;
640 if (pos.slice(0,5)=="below") dy = fontsize-0;
641 if (pos.slice(0,5)=="right" || pos.slice(5,10)=="right") {
642 textanchor = "start";
645 if (pos.slice(0,4)=="left" || pos.slice(5,9)=="left") {
651 if (id!=null) node = doc.getElementById(id);
653 node = myCreateElementSVG("text");
654 node.setAttribute("id", id);
655 svgpicture.appendChild(node);
656 node.appendChild(doc.createTextNode(st));
658 node.lastChild.nodeValue = st;
659 node.setAttribute("x",p[0]*xunitlength+origin[0]+dx);
660 node.setAttribute("y",height-p[1]*yunitlength-origin[1]+dy);
661 node.setAttribute("font-style",(fontsty!=null?fontsty:fontstyle));
662 node.setAttribute("font-family",fontfamily);
663 node.setAttribute("font-size",fontsize);
664 node.setAttribute("font-weight",fontweight);
665 node.setAttribute("text-anchor",textanchor);
666 if (fontstroke!="none") node.setAttribute("stroke",fontstroke);
667 if (fontfill!="none") node.setAttribute("fill",fontfill);
671 function ASdot(center,radius,s,f) { // coordinates in units, radius in pixel
672 if (s==null) s = stroke; if (f==null) f = fill;
673 var node = myCreateElementSVG("circle");
674 node.setAttribute("cx",center[0]*xunitlength+origin[0]);
675 node.setAttribute("cy",height-center[1]*yunitlength-origin[1]);
676 node.setAttribute("r",radius);
677 node.setAttribute("stroke-width", strokewidth);
678 node.setAttribute("stroke", s);
679 node.setAttribute("fill", f);
680 svgpicture.appendChild(node);
683 function dot(center, typ, label, pos, id) {
685 var cx = center[0]*xunitlength+origin[0];
686 var cy = height-center[1]*yunitlength-origin[1];
687 if (id!=null) node = doc.getElementById(id);
688 if (typ=="+" || typ=="-" || typ=="|") {
690 node = myCreateElementSVG("path");
691 node.setAttribute("id", id);
692 svgpicture.appendChild(node);
695 node.setAttribute("d",
696 " M "+(cx-ticklength)+" "+cy+" L "+(cx+ticklength)+" "+cy+
697 " M "+cx+" "+(cy-ticklength)+" L "+cx+" "+(cy+ticklength));
698 node.setAttribute("stroke-width", .5);
699 node.setAttribute("stroke", axesstroke);
701 if (typ=="-") node.setAttribute("d",
702 " M "+(cx-ticklength)+" "+cy+" L "+(cx+ticklength)+" "+cy);
703 else node.setAttribute("d",
704 " M "+cx+" "+(cy-ticklength)+" L "+cx+" "+(cy+ticklength));
705 node.setAttribute("stroke-width", strokewidth);
706 node.setAttribute("stroke", stroke);
710 node = myCreateElementSVG("circle");
711 node.setAttribute("id", id);
712 svgpicture.appendChild(node);
714 node.setAttribute("cx",cx);
715 node.setAttribute("cy",cy);
716 node.setAttribute("r",dotradius);
717 node.setAttribute("stroke-width", strokewidth);
718 node.setAttribute("stroke", stroke);
719 node.setAttribute("fill", (typ=="open"?"white":stroke));
722 text(center,label,(pos==null?"below":pos),(id==null?id:id+"label"))
725 function arrowhead(p,q) { // draw arrowhead at q (in units)
727 var v = [p[0]*xunitlength+origin[0],height-p[1]*yunitlength-origin[1]];
728 var w = [q[0]*xunitlength+origin[0],height-q[1]*yunitlength-origin[1]];
729 var u = [w[0]-v[0],w[1]-v[1]];
730 var d = Math.sqrt(u[0]*u[0]+u[1]*u[1]);
731 if (d > 0.00000001) {
732 u = [u[0]/d, u[1]/d];
734 var node = myCreateElementSVG("path");
735 node.setAttribute("d","M "+(w[0]-15*u[0]-4*up[0])+" "+
736 (w[1]-15*u[1]-4*up[1])+" L "+(w[0]-3*u[0])+" "+(w[1]-3*u[1])+" L "+
737 (w[0]-15*u[0]+4*up[0])+" "+(w[1]-15*u[1]+4*up[1])+" z");
738 node.setAttribute("stroke-width", markerstrokewidth);
739 node.setAttribute("stroke", stroke); /*was markerstroke*/
740 node.setAttribute("fill", stroke); /*was arrowfill*/
741 svgpicture.appendChild(node);
746 var k = st.indexOf(".");
747 if (k==-1) return st;
748 for (var i=st.length-1; i>k && st.charAt(i)=="0"; i--);
750 return st.slice(0,i+1);
753 function grid(dx,dy) { // for backward compatibility
754 axes(dx,dy,null,dx,dy)
758 if (!initialized) initPicture();
761 function axes(dx,dy,labels,gdx,gdy) {
762 //xscl=x is equivalent to xtick=x; xgrid=x; labels=true;
763 var x, y, ldx, ldy, lx, ly, lxp, lyp, pnode, st;
764 if (!initialized) initPicture();
765 if (typeof dx=="string") { labels = dx; dx = null; }
766 if (typeof dy=="string") { gdx = dy; dy = null; }
767 if (xscl!=null) {dx = xscl; gdx = xscl; labels = dx}
768 if (yscl!=null) {dy = yscl; gdy = yscl}
769 if (xtick!=null) {dx = xtick}
770 if (ytick!=null) {dy = ytick}
772 dx = (dx==null?xunitlength:dx*xunitlength);
773 dy = (dy==null?dx:dy*yunitlength);
774 fontsize = Math.min(dx/2,dy/2,16);//alert(fontsize)
775 ticklength = fontsize/4;
776 if (xgrid!=null) gdx = xgrid;
777 if (ygrid!=null) gdy = ygrid;
779 gdx = (typeof gdx=="string"?dx:gdx*xunitlength);
780 gdy = (gdy==null?dy:gdy*yunitlength);
781 pnode = myCreateElementSVG("path");
783 for (x = origin[0]; x<width; x = x+gdx)
784 st += " M"+x+",0"+" "+x+","+height;
785 for (x = origin[0]-gdx; x>0; x = x-gdx)
786 st += " M"+x+",0"+" "+x+","+height;
787 for (y = height-origin[1]; y<height; y = y+gdy)
788 st += " M0,"+y+" "+width+","+y;
789 for (y = height-origin[1]-gdy; y>0; y = y-gdy)
790 st += " M0,"+y+" "+width+","+y;
791 pnode.setAttribute("d",st);
792 pnode.setAttribute("stroke-width", .5);
793 pnode.setAttribute("stroke", gridstroke);
794 pnode.setAttribute("fill", fill);
795 svgpicture.appendChild(pnode);
797 pnode = myCreateElementSVG("path");
798 st="M0,"+(height-origin[1])+" "+width+","+
799 (height-origin[1])+" M"+origin[0]+",0 "+origin[0]+","+height;
800 for (x = origin[0]+dx; x<width; x = x+dx)
801 st += " M"+x+","+(height-origin[1]+ticklength)+" "+x+","+
802 (height-origin[1]-ticklength);
803 for (x = origin[0]-dx; x>0; x = x-dx)
804 st += " M"+x+","+(height-origin[1]+ticklength)+" "+x+","+
805 (height-origin[1]-ticklength);
806 for (y = height-origin[1]+dy; y<height; y = y+dy)
807 st += " M"+(origin[0]+ticklength)+","+y+" "+(origin[0]-ticklength)+","+y;
808 for (y = height-origin[1]-dy; y>0; y = y-dy)
809 st += " M"+(origin[0]+ticklength)+","+y+" "+(origin[0]-ticklength)+","+y;
810 if (labels!=null) with (Math) {
811 ldx = dx/xunitlength;
812 ldy = dy/yunitlength;
813 lx = (xmin>0 || xmax<0?xmin:0);
814 ly = (ymin>0 || ymax<0?ymin:0);
815 lxp = (ly==0?"below":"above");
816 lyp = (lx==0?"left":"right");
817 var ddx = floor(1.1-log(ldx)/log(10))+1;
818 var ddy = floor(1.1-log(ldy)/log(10))+1;
819 for (x = ldx; x<=xmax; x = x+ldx)
820 text([x,ly],chopZ(x.toFixed(ddx)),lxp);
821 for (x = -ldx; xmin<=x; x = x-ldx)
822 text([x,ly],chopZ(x.toFixed(ddx)),lxp);
823 for (y = ldy; y<=ymax; y = y+ldy)
824 text([lx,y],chopZ(y.toFixed(ddy)),lyp);
825 for (y = -ldy; ymin<=y; y = y-ldy)
826 text([lx,y],chopZ(y.toFixed(ddy)),lyp);
828 pnode.setAttribute("d",st);
829 pnode.setAttribute("stroke-width", .5);
830 pnode.setAttribute("stroke", axesstroke);
831 pnode.setAttribute("fill", fill);
832 svgpicture.appendChild(pnode);
835 function mathjs(st) {
836 //translate a math formula to js function notation
839 // (...)d --> (...)*d
840 // n! --> factorial(n)
841 // sin^-1 --> arcsin etc.
842 //while ^ in string, find term on left and right
843 //slice and concat new formula string
844 st = st.replace(/\s/g,"");
845 if (st.indexOf("^-1")!=-1) {
846 st = st.replace(/sin\^-1/g,"arcsin");
847 st = st.replace(/cos\^-1/g,"arccos");
848 st = st.replace(/tan\^-1/g,"arctan");
849 st = st.replace(/sec\^-1/g,"arcsec");
850 st = st.replace(/csc\^-1/g,"arccsc");
851 st = st.replace(/cot\^-1/g,"arccot");
852 st = st.replace(/sinh\^-1/g,"arcsinh");
853 st = st.replace(/cosh\^-1/g,"arccosh");
854 st = st.replace(/tanh\^-1/g,"arctanh");
855 st = st.replace(/sech\^-1/g,"arcsech");
856 st = st.replace(/csch\^-1/g,"arccsch");
857 st = st.replace(/coth\^-1/g,"arccoth");
859 st = st.replace(/^e$/g,"(E)");
860 st = st.replace(/^e([^a-zA-Z])/g,"(E)$1");
861 st = st.replace(/([^a-zA-Z])e([^a-zA-Z])/g,"$1(E)$2");
862 st = st.replace(/([0-9])([\(a-zA-Z])/g,"$1*$2");
863 st = st.replace(/\)([\(0-9a-zA-Z])/g,"\)*$1");
864 var i,j,k, ch, nested;
865 while ((i=st.indexOf("^"))!=-1) {
867 if (i==0) return "Error: missing argument";
870 if (ch>="0" && ch<="9") {// look for (decimal) number
872 while (j>=0 && (ch=st.charAt(j))>="0" && ch<="9") j--;
875 while (j>=0 && (ch=st.charAt(j))>="0" && ch<="9") j--;
877 } else if (ch==")") {// look for matching opening bracket and function name
880 while (j>=0 && nested>0) {
882 if (ch=="(") nested--;
883 else if (ch==")") nested++;
886 while (j>=0 && (ch=st.charAt(j))>="a" && ch<="z" || ch>="A" && ch<="Z")
888 } else if (ch>="a" && ch<="z" || ch>="A" && ch<="Z") {// look for variable
890 while (j>=0 && (ch=st.charAt(j))>="a" && ch<="z" || ch>="A" && ch<="Z")
893 return "Error: incorrect syntax in "+st+" at position "+j;
895 //find right argument
896 if (i==st.length-1) return "Error: missing argument";
899 if (ch>="0" && ch<="9" || ch=="-") {// look for signed (decimal) number
901 while (k<st.length && (ch=st.charAt(k))>="0" && ch<="9") k++;
904 while (k<st.length && (ch=st.charAt(k))>="0" && ch<="9") k++;
906 } else if (ch=="(") {// look for matching closing bracket and function name
909 while (k<st.length && nested>0) {
911 if (ch=="(") nested++;
912 else if (ch==")") nested--;
915 } else if (ch>="a" && ch<="z" || ch>="A" && ch<="Z") {// look for variable
917 while (k<st.length && (ch=st.charAt(k))>="a" && ch<="z" ||
918 ch>="A" && ch<="Z") k++;
920 return "Error: incorrect syntax in "+st+" at position "+k;
922 st = st.slice(0,j+1)+"pow("+st.slice(j+1,i)+","+st.slice(i+1,k)+")"+
925 while ((i=st.indexOf("!"))!=-1) {
927 if (i==0) return "Error: missing argument";
930 if (ch>="0" && ch<="9") {// look for (decimal) number
932 while (j>=0 && (ch=st.charAt(j))>="0" && ch<="9") j--;
935 while (j>=0 && (ch=st.charAt(j))>="0" && ch<="9") j--;
937 } else if (ch==")") {// look for matching opening bracket and function name
940 while (j>=0 && nested>0) {
942 if (ch=="(") nested--;
943 else if (ch==")") nested++;
946 while (j>=0 && (ch=st.charAt(j))>="a" && ch<="z" || ch>="A" && ch<="Z")
948 } else if (ch>="a" && ch<="z" || ch>="A" && ch<="Z") {// look for variable
950 while (j>=0 && (ch=st.charAt(j))>="a" && ch<="z" || ch>="A" && ch<="Z")
953 return "Error: incorrect syntax in "+st+" at position "+j;
955 st = st.slice(0,j+1)+"factorial("+st.slice(j+1,i)+")"+st.slice(i+1);
960 function plot(fun,x_min,x_max,points,id) {
962 var f = function(x) { return x }, g = fun;
964 if (typeof fun=="string")
965 eval("g = function(x){ with(Math) return "+mathjs(fun)+" }");
966 else if (typeof fun=="object") {
967 eval("f = function(t){ with(Math) return "+mathjs(fun[0])+" }");
968 eval("g = function(t){ with(Math) return "+mathjs(fun[1])+" }");
970 if (typeof x_min=="string") { name = x_min; x_min = xmin }
972 var min = (x_min==null?xmin:x_min);
973 var max = (x_max==null?xmax:x_max);
974 var inc = max-min-0.000001*(max-min);
975 inc = (points==null?inc/200:inc/points);
977 //alert(typeof g(min))
978 for (var t = min; t <= max; t += inc) {
980 if (!(isNaN(gt)||Math.abs(gt)=="Infinity")) pth[pth.length] = [f(t), gt];
986 function slopefield(fun,dx,dy) {
988 if (typeof fun=="string")
989 eval("g = function(x,y){ with(Math) return "+mathjs(fun)+" }");
993 dz = Math.sqrt(dx*dx+dy*dy)/6;
994 var x_min = Math.ceil(xmin/dx);
995 var y_min = Math.ceil(ymin/dy);
996 for (x = x_min; x <= xmax; x += dx)
997 for (y = y_min; y <= ymax; y += dy) {
1000 if (Math.abs(gxy)=="Infinity") {u = 0; v = dz;}
1001 else {u = dz/Math.sqrt(1+gxy*gxy); v = gxy*u;}
1002 line([x-u,y-v],[x+u,y+v]);
1007 function updateCoords(ind) {
1008 switchTo("picture"+(ind+1));
1009 var gx=getX(), gy=getY();
1010 if ((xmax-gx)*xunitlength > 6*fontsize || (gy-ymin)*yunitlength > 2*fontsize)
1011 text([xmax,ymin],"("+gx.toFixed(2)+", "+gy.toFixed(2)+")",
1012 "aboveleft","AScoord"+ind,"");
1013 else text([xmax,ymin]," ","aboveleft","AScoord"+ind,"");
1016 function updateCoords0() {updateCoords(0)}
1017 function updateCoords1() {updateCoords(1)}
1018 function updateCoords2() {updateCoords(2)}
1019 function updateCoords3() {updateCoords(3)}
1020 function updateCoords4() {updateCoords(4)}
1021 function updateCoords5() {updateCoords(5)}
1022 function updateCoords6() {updateCoords(6)}
1023 function updateCoords7() {updateCoords(7)}
1024 function updateCoords8() {updateCoords(8)}
1025 function updateCoords9() {updateCoords(9)}
1026 ASfn = [function() {updatePicture(0)},
1027 function() {updatePicture(1)},
1028 function() {updatePicture(2)},
1029 function() {updatePicture(3)},
1030 function() {updatePicture(4)},
1031 function() {updatePicture(5)},
1032 function() {updatePicture(6)},
1033 function() {updatePicture(7)},
1034 function() {updatePicture(8)},
1035 function() {updatePicture(9)}];
1036 ASupdateCoords = [function() {updateCoords(0)},
1037 function() {updateCoords(1)},
1038 function() {updateCoords(2)},
1039 function() {updateCoords(3)},
1040 function() {updateCoords(4)},
1041 function() {updateCoords(5)},
1042 function() {updateCoords(6)},
1043 function() {updateCoords(7)},
1044 function() {updateCoords(8)},
1045 function() {updateCoords(9)}];
1047 // GO1.1 Generic onload by Brothercake
1048 // http://www.brothercake.com/
1054 //setup onload function
1055 if(typeof window.addEventListener != 'undefined')
1057 //.. gecko, safari, konqueror and standard
1058 window.addEventListener('load', generic, false);
1060 else if(typeof document.addEventListener != 'undefined')
1063 document.addEventListener('load', generic, false);
1065 else if(typeof window.attachEvent != 'undefined')
1068 window.attachEvent('onload', generic);
1070 //** remove this condition to degrade older browsers
1073 //.. mac/ie5 and anything else that gets this far
1074 //if there's an existing onload function
1075 if(typeof window.onload == 'function')
1078 var existing = onload;
1079 //add new onload handler
1080 window.onload = function()
1082 //call existing onload function
1084 //call generic onload function
1090 //setup onload function
1091 window.onload = generic;