2 * Raphaël 2.0.0 - JavaScript Vector Library
4 * Copyright (c) 2011 Dmitry Baranovskiy (http://raphaeljs.com)
5 * Copyright (c) 2011 Sencha Labs (http://sencha.com)
6 * Licensed under the MIT (http://raphaeljs.com/license.html) license.
13 * Creates a canvas object on which to draw.
14 * You must do this first, as all future calls to drawing methods
15 * from this instance will be bound to this canvas.
18 - container (HTMLElement|string) DOM element or its ID which is going to be a parent for drawing surface
21 - callback (function) #optional callback function which is going to be executed in the context of newly created paper
27 - callback (function) #optional callback function which is going to be executed in the context of newly created paper
29 - all (array) (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>})
30 - callback (function) #optional callback function which is going to be executed in the context of newly created paper
32 - onReadyCallback (function) function that is going to be called on DOM ready event. You can also subscribe to this event via Eve’s “DOMLoad” event. In this case method returns `undefined`.
35 | // Each of the following examples create a canvas
36 | // that is 320px wide by 200px high.
37 | // Canvas is created at the viewport’s 10,50 coordinate.
38 | var paper = Raphael(10, 50, 320, 200);
39 | // Canvas is created at the top left corner of the #notepad element
40 | // (or its top right corner in dir="rtl" elements)
41 | var paper = Raphael(document.getElementById("notepad"), 320, 200);
43 | var paper = Raphael("notepad", 320, 200);
45 | var set = Raphael(["notepad", 320, 200, {
60 if (R.is(first, "function")) {
61 return loaded ? first() : eve.on("DOMload", first);
62 } else if (R.is(first, array)) {
64 cnv = create[apply](R, a.splice(0, 3 + R.is(a[0], nu))),
71 elements[has](j.type) && res.push(cnv[j.type]().attr(j));
75 var args = Array.prototype.slice.call(arguments, 0);
76 if (R.is(args[args.length - 1], "function")) {
78 return loaded ? f.call(create[apply](R, args)) : eve.on("DOMload", function () {
79 f.call(create[apply](R, args));
82 return create[apply](R, arguments);
89 elements = {circle: 1, rect: 1, path: 1, ellipse: 1, text: 1, image: 1},
90 formatrg = /\{(\d+)\}/g,
92 has = "hasOwnProperty",
98 was: Object.prototype[has].call(g.win, "Raphael"),
101 Paper = function () {},
103 appendChild = "appendChild",
106 supportsTouch = "createTouch" in g.doc,
111 events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend orientationchange touchcancel gesturestart gesturechange gestureend".split(S),
113 mousedown: "touchstart",
114 mousemove: "touchmove",
117 lowerCase = Str.prototype.toLowerCase,
127 toString = "toString",
129 objectToString = Object.prototype.toString,
132 ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
133 colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,
134 isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1},
135 bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
137 setAttribute = "setAttribute",
138 toFloat = parseFloat,
140 ms = " progid:DXImageTransform.Microsoft",
141 upperCase = Str.prototype.toUpperCase,
142 availableAttrs = {"arrow-end": "none", "arrow-start": "none", blur: 0, "clip-rect": "0 0 1e9 1e9", cursor: "default", cx: 0, cy: 0, fill: "#fff", "fill-opacity": 1, font: '10px "Arial"', "font-family": '"Arial"', "font-size": "10", "font-style": "normal", "font-weight": 400, gradient: 0, height: 0, href: "http://raphaeljs.com/", opacity: 1, path: "M0,0", r: 0, rx: 0, ry: 0, src: "", stroke: "#000", "stroke-dasharray": "", "stroke-linecap": "butt", "stroke-linejoin": "butt", "stroke-miterlimit": 0, "stroke-opacity": 1, "stroke-width": 1, target: "_blank", "text-anchor": "middle", title: "Raphael", transform: "", width: 0, x: 0, y: 0},
143 availableAnimAttrs = {blur: nu, "clip-rect": "csv", cx: nu, cy: nu, fill: "colour", "fill-opacity": nu, "font-size": nu, height: nu, opacity: nu, path: "path", r: nu, rx: nu, ry: nu, stroke: "colour", "stroke-opacity": nu, "stroke-width": nu, transform: "transform", width: nu, x: nu, y: nu},
144 commaSpaces = /\s*,\s*/,
145 hsrg = {hs: 1, rg: 1},
146 p2s = /,?([achlmqrstvxz]),?/gi,
147 pathCommand = /([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[-+]?\d+)?\s*,?\s*)+)/ig,
148 tCommand = /([rstm])[\s,]*((-?\d*\.?\d*(?:e[-+]?\d+)?\s*,?\s*)+)/ig,
149 pathValues = /(-?\d*\.?\d*(?:e[-+]?\d+)?)\s*,?\s*/ig,
150 radial_gradient = /^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/,
151 sortByKey = function (a, b) {
152 return a.key - b.key;
154 sortByNumber = function (a, b) {
157 fun = function () {},
158 pipe = function (x) {
161 rectPath = function (x, y, w, h, r) {
163 return [["M", x + r, y], ["l", w - r * 2, 0], ["a", r, r, 0, 0, 1, r, r], ["l", 0, h - r * 2], ["a", r, r, 0, 0, 1, -r, r], ["l", r * 2 - w, 0], ["a", r, r, 0, 0, 1, -r, -r], ["l", 0, r * 2 - h], ["a", r, r, 0, 0, 1, r, -r], ["z"]];
165 return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
167 ellipsePath = function (x, y, rx, ry) {
171 return [["M", x, y], ["m", 0, -ry], ["a", rx, ry, 0, 1, 1, 0, 2 * ry], ["a", rx, ry, 0, 1, 1, 0, -2 * ry], ["z"]];
174 path: function (el) {
175 return el.attr("path");
177 circle: function (el) {
179 return ellipsePath(a.cx, a.cy, a.r);
181 ellipse: function (el) {
183 return ellipsePath(a.cx, a.cy, a.rx, a.ry);
185 rect: function (el) {
187 return rectPath(a.x, a.y, a.width, a.height, a.r);
189 image: function (el) {
191 return rectPath(a.x, a.y, a.width, a.height);
193 text: function (el) {
194 var bbox = el._getBBox();
195 return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
198 mapPath = function (path, matrix) {
202 var x, y, i, j, pathi;
203 path = path2curve(path);
204 for (i = 0, ii = path.length; i < ii; i++) {
206 for (j = 1, jj = pathi.length; j < jj; j += 2) {
207 x = matrix.x(pathi[j], pathi[j + 1]);
208 y = matrix.y(pathi[j], pathi[j + 1]);
218 [ property (string) ]
220 * Can be “SVG”, “VML” or empty, depending on browser support.
222 R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML");
223 if (R.type == "VML") {
224 var d = g.doc.createElement("div"),
226 d.innerHTML = '<v:shape adj="1"/>';
228 b.style.behavior = "url(#default#VML)";
229 if (!(b && typeof b.adj == "object")) {
236 [ property (boolean) ]
238 * `true` if browser supports SVG.
242 [ property (boolean) ]
244 * `true` if browser supports VML.
246 R.svg = !(R.vml = R.type == "VML");
247 paperproto = Paper.prototype = R.prototype;
249 * Paper.customAttributes
250 [ property (object) ]
252 * If you have a set of attributes that you would like to represent
253 * as a function of some number you can do it easily with custom attributes:
255 | paper.customAttributes.hue = function (num) {
257 | return {fill: "hsb(" + num + ", .75, 1)"};
259 | // Custom attribute “hue” will change fill
260 | // to be given hue with fixed saturation and brightness.
261 | // Now you can use it like this:
262 | var c = paper.circle(10, 10, 10).attr({hue: .45});
263 | // or even like this:
264 | c.animate({hue: 1}, 1e3);
266 | // You could also create custom attribute
267 | // with multiple parameters:
268 | paper.customAttributes.hsb = function (h, s, b) {
269 | return {fill: "hsb(" + [h, s, b].join(",") + ")"};
271 | c.attr({hsb: ".5 .8 1"});
272 | c.animate({hsb: "1 0 .5"}, 1e3);
274 paperproto.customAttributes = {};
279 [ property (object) ]
281 * You can add your own method to the canvas. For example if you want to draw a pie chart,
282 * you can create your own pie chart function and ship it as a Raphaël plugin. To do this
283 * you need to extend the `Raphael.fn` object. Please note that you can create your own namespaces
284 * inside the `fn` object — methods will be run in the context of canvas anyway. You should alter
285 * the `fn` object before a Raphaël instance is created, otherwise it will take no effect.
287 | Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
288 | return this.path( ... );
290 | // or create namespace
291 | Raphael.fn.mystuff = {
292 | arrow: function () {…},
293 | star: function () {…},
296 | var paper = Raphael(10, 10, 630, 480);
298 | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
299 | paper.mystuff.arrow();
300 | paper.mystuff.star();
307 * Handfull replacement for `typeof` operator.
309 - o (…) any object or primitive
310 - type (string) name of the type, i.e. “string”, “function”, “number”, etc.
311 = (boolean) is given value is of given type
313 R.is = function (o, type) {
314 type = lowerCase.call(type);
315 if (type == "finite") {
316 return !isnan[has](+o);
318 return (type == "null" && o === null) ||
319 (type == typeof o) ||
320 (type == "object" && o === Object(o)) ||
321 (type == "array" && Array.isArray && Array.isArray(o)) ||
322 objectToString.call(o).slice(8, -1).toLowerCase() == type;
328 * Returns angle between two or three points
330 - x1 (number) x coord of first point
331 - y1 (number) y coord of first point
332 - x2 (number) x coord of second point
333 - y2 (number) y coord of second point
334 - x3 (number) #optional x coord of third point
335 - y3 (number) #optional y coord of third point
336 = (number) angle in degrees.
338 R.angle = function (x1, y1, x2, y2, x3, y3) {
345 return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
347 return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3);
354 * Transform angle to radians
356 - deg (number) angle in degrees
357 = (number) angle in radians.
359 R.rad = function (deg) {
360 return deg % 360 * PI / 180;
366 * Transform angle to degrees
368 - deg (number) angle in radians
369 = (number) angle in degrees.
371 R.deg = function (rad) {
372 return rad * 180 / PI % 360;
378 * Snaps given value to given grid.
380 - values (array|number) given array of values or step of the grid
381 - value (number) value to adjust
382 - tolerance (number) #optional tolerance for snapping. Default is `10`.
383 = (number) adjusted value.
385 R.snapTo = function (values, value, tolerance) {
386 tolerance = R.is(tolerance, "finite") ? tolerance : 10;
387 if (R.is(values, array)) {
388 var i = values.length;
389 while (i--) if (abs(values[i] - value) <= tolerance) {
394 var rem = value % values;
395 if (rem < tolerance) {
398 if (rem > values - tolerance) {
399 return value - rem + values;
405 var createUUID = (function (uuidRegEx, uuidReplacer) {
407 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
409 })(/[xy]/g, function (c) {
410 var r = math.random() * 16 | 0,
411 v = c == "x" ? r : (r & 3 | 8);
412 return v.toString(16);
419 * Used when you need to draw in `<iframe>`. Switched window to the iframe one.
421 - newwin (window) new window object
423 R.setWindow = function (newwin) {
424 eve("setWindow", R, g.win, newwin);
426 g.doc = g.win.document;
432 var toHex = function (color) {
434 // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/
435 var trim = /^\s+|\s+$/g;
438 var docum = new ActiveXObject("htmlfile");
439 docum.write("<body>");
443 bod = createPopup().document.body;
445 var range = bod.createTextRange();
446 toHex = cacher(function (color) {
448 bod.style.color = Str(color).replace(trim, E);
449 var value = range.queryCommandValue("ForeColor");
450 value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16);
451 return "#" + ("000000" + value.toString(16)).slice(-6);
457 var i = g.doc.createElement("i");
458 i.title = "Rapha\xebl Colour Picker";
459 i.style.display = "none";
460 g.doc.body.appendChild(i);
461 toHex = cacher(function (color) {
462 i.style.color = color;
463 return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
468 hsbtoString = function () {
469 return "hsb(" + [this.h, this.s, this.b] + ")";
471 hsltoString = function () {
472 return "hsl(" + [this.h, this.s, this.l] + ")";
474 rgbtoString = function () {
477 prepareRGB = function (r, g, b) {
478 if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
483 if (g == null && R.is(r, string)) {
484 var clr = R.getRGB(r);
489 if (r > 1 || g > 1 || b > 1) {
497 packageRGB = function (r, g, b, o) {
506 toString: rgbtoString
508 R.is(o, "finite") && (rgb.opacity = o);
515 * Converts HSB values to RGB object.
518 - s (number) saturation
519 - v (number) value or brightness
520 = (object) RGB object in format:
525 o hex (string) color in HTML/CSS format: #••••••
528 R.hsb2rgb = function (h, s, v, o) {
529 if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
539 X = C * (1 - abs(h % 2 - 1));
543 R += [C, X, 0, 0, X, C][h];
544 G += [X, C, C, X, 0, 0][h];
545 B += [0, 0, X, C, C, X][h];
546 return packageRGB(R, G, B, o);
552 * Converts HSL values to RGB object.
555 - s (number) saturation
556 - l (number) luminosity
557 = (object) RGB object in format:
562 o hex (string) color in HTML/CSS format: #••••••
565 R.hsl2rgb = function (h, s, l, o) {
566 if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
571 if (h > 1 || s > 1 || l > 1) {
579 C = 2 * s * (l < .5 ? l : 1 - l);
580 X = C * (1 - abs(h % 2 - 1));
581 R = G = B = l - C / 2;
584 R += [C, X, 0, 0, X, C][h];
585 G += [X, C, C, X, 0, 0][h];
586 B += [0, 0, X, C, C, X][h];
587 return packageRGB(R, G, B, o);
593 * Converts RGB values to HSB object.
598 = (object) HSB object in format:
601 o s (number) saturation
602 o b (number) brightness
605 R.rgb2hsb = function (r, g, b) {
606 b = prepareRGB(r, g, b);
613 C = V - mmin(r, g, b);
615 V == r ? (g - b) / C :
616 V == g ? (b - r) / C + 2 :
619 S = C == 0 ? 0 : C / V;
620 return {h: H, s: S, b: V, toString: hsbtoString};
626 * Converts RGB values to HSL object.
631 = (object) HSL object in format:
634 o s (number) saturation
635 o l (number) luminosity
638 R.rgb2hsl = function (r, g, b) {
639 b = prepareRGB(r, g, b);
644 var H, S, L, M, m, C;
649 M == r ? (g - b) / C :
650 M == g ? (b - r) / C + 2 :
655 L < .5 ? C / (2 * L) :
657 return {h: H, s: S, l: L, toString: hsltoString};
659 R._path2string = function () {
660 return this.join(",").replace(p2s, "$1");
662 function cacher(f, scope, postprocessor) {
664 var arg = Array.prototype.slice.call(arguments, 0),
665 args = arg.join("\u2400"),
666 cache = newf.cache = newf.cache || {},
667 count = newf.count = newf.count || [];
668 if (cache[has](args)) {
669 return postprocessor ? postprocessor(cache[args]) : cache[args];
671 count.length >= 1e3 && delete cache[count.shift()];
673 cache[args] = f[apply](scope, arg);
674 return postprocessor ? postprocessor(cache[args]) : cache[args];
679 function preload(src, f) {
680 var img = g.doc.createElement("img");
681 img.style.cssText = "position:absolute;left:-9999em;top-9999em";
682 img.onload = function () {
685 g.doc.body.removeChild(this);
687 img.onerror = function () {
688 g.doc.body.removeChild(this);
690 g.doc.body.appendChild(img);
698 * Parses colour string as RGB object
700 - colour (string) colour string in one of formats:
702 # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
703 # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
704 # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
705 # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
706 # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
707 # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
708 # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
709 # <li>hsl(•••, •••, •••) — same as hsb</li>
710 # <li>hsl(•••%, •••%, •••%) — same as hsb</li>
712 = (object) RGB object in format:
717 o hex (string) color in HTML/CSS format: #••••••,
718 o error (boolean) true if string can’t be parsed
721 R.getRGB = cacher(function (colour) {
722 if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
723 return {r: -1, g: -1, b: -1, hex: "none", error: 1};
725 if (colour == "none") {
726 return {r: -1, g: -1, b: -1, hex: "none"};
728 !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
736 rgb = colour.match(colourRegExp);
739 blue = toInt(rgb[2].substring(5), 16);
740 green = toInt(rgb[2].substring(3, 5), 16);
741 red = toInt(rgb[2].substring(1, 3), 16);
744 blue = toInt((t = rgb[3].charAt(3)) + t, 16);
745 green = toInt((t = rgb[3].charAt(2)) + t, 16);
746 red = toInt((t = rgb[3].charAt(1)) + t, 16);
749 values = rgb[4].split(commaSpaces);
750 red = toFloat(values[0]);
751 values[0].slice(-1) == "%" && (red *= 2.55);
752 green = toFloat(values[1]);
753 values[1].slice(-1) == "%" && (green *= 2.55);
754 blue = toFloat(values[2]);
755 values[2].slice(-1) == "%" && (blue *= 2.55);
756 rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
757 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
760 values = rgb[5].split(commaSpaces);
761 red = toFloat(values[0]);
762 values[0].slice(-1) == "%" && (red *= 2.55);
763 green = toFloat(values[1]);
764 values[1].slice(-1) == "%" && (green *= 2.55);
765 blue = toFloat(values[2]);
766 values[2].slice(-1) == "%" && (blue *= 2.55);
767 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
768 rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
769 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
770 return R.hsb2rgb(red, green, blue, opacity);
773 values = rgb[6].split(commaSpaces);
774 red = toFloat(values[0]);
775 values[0].slice(-1) == "%" && (red *= 2.55);
776 green = toFloat(values[1]);
777 values[1].slice(-1) == "%" && (green *= 2.55);
778 blue = toFloat(values[2]);
779 values[2].slice(-1) == "%" && (blue *= 2.55);
780 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
781 rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
782 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
783 return R.hsl2rgb(red, green, blue, opacity);
785 rgb = {r: red, g: green, b: blue};
786 rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
787 R.is(opacity, "finite") && (rgb.opacity = opacity);
790 return {r: -1, g: -1, b: -1, hex: "none", error: 1};
796 * Converts HSB values to hex representation of the colour.
799 - s (number) saturation
800 - b (number) value or brightness
801 = (string) hex representation of the colour.
803 R.hsb = cacher(function (h, s, b) {
804 return R.hsb2rgb(h, s, b).hex;
810 * Converts HSL values to hex representation of the colour.
813 - s (number) saturation
814 - l (number) luminosity
815 = (string) hex representation of the colour.
817 R.hsl = cacher(function (h, s, l) {
818 return R.hsl2rgb(h, s, l).hex;
824 * Converts RGB values to hex representation of the colour.
829 = (string) hex representation of the colour.
831 R.rgb = cacher(function (r, g, b) {
832 return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
838 * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset
840 - value (number) #optional brightness, default is `0.75`
841 = (string) hex representation of the colour.
843 R.getColor = function (value) {
844 var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75},
845 rgb = this.hsb2rgb(start.h, start.s, start.b);
850 start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b});
855 * Raphael.getColor.reset
858 * Resets spectrum position for @Raphael.getColor back to red.
860 R.getColor.reset = function () {
865 * Raphael.parsePathString
870 * Parses given path string into an array of arrays of path segments.
872 - pathString (string|array) path string or array of segments (in the last case it will be returned straight away)
873 = (array) array of segments.
875 R.parsePathString = cacher(function (pathString) {
879 var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0},
881 if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption
882 data = pathClone(pathString);
885 Str(pathString).replace(pathCommand, function (a, b, c) {
887 name = lowerCase.call(b);
888 c.replace(pathValues, function (a, b) {
889 b && params.push(+b);
891 if (name == "m" && params.length > 2) {
892 data.push([b][concat](params.splice(0, 2)));
894 b = b == "m" ? "l" : "L";
896 while (params.length >= paramCounts[name]) {
897 data.push([b][concat](params.splice(0, paramCounts[name])));
898 if (!paramCounts[name]) {
904 data.toString = R._path2string;
908 * Raphael.parseTransformString
913 * Parses given path string into an array of transformations.
915 - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away)
916 = (array) array of transformations.
918 R.parseTransformString = cacher(function (TString) {
922 var paramCounts = {r: 3, s: 4, t: 2, m: 6},
924 if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption
925 data = pathClone(TString);
928 Str(TString).replace(tCommand, function (a, b, c) {
930 name = lowerCase.call(b);
931 c.replace(pathValues, function (a, b) {
932 b && params.push(+b);
934 data.push([name][concat](params));
937 data.toString = R._path2string;
941 * Raphael.findDotsAtSegment
946 * Find dot coordinates on the given cubic bezier curve at the given t.
948 - p1x (number) x of the first point of the curve
949 - p1y (number) y of the first point of the curve
950 - c1x (number) x of the first anchor of the curve
951 - c1y (number) y of the first anchor of the curve
952 - c2x (number) x of the second anchor of the curve
953 - c2y (number) y of the second anchor of the curve
954 - p2x (number) x of the second point of the curve
955 - p2y (number) y of the second point of the curve
956 - t (number) position on the curve (0..1)
957 = (object) point information in format:
959 o x: (number) x coordinate of the point
960 o y: (number) y coordinate of the point
962 o x: (number) x coordinate of the left anchor
963 o y: (number) y coordinate of the left anchor
966 o x: (number) x coordinate of the right anchor
967 o y: (number) y coordinate of the right anchor
970 o x: (number) x coordinate of the start of the curve
971 o y: (number) y coordinate of the start of the curve
974 o x: (number) x coordinate of the end of the curve
975 o y: (number) y coordinate of the end of the curve
977 o alpha: (number) angle of the curve derivative at the point
980 R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
982 x = pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
983 y = pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y,
984 mx = p1x + 2 * t * (c1x - p1x) + t * t * (c2x - 2 * c1x + p1x),
985 my = p1y + 2 * t * (c1y - p1y) + t * t * (c2y - 2 * c1y + p1y),
986 nx = c1x + 2 * t * (c2x - c1x) + t * t * (p2x - 2 * c2x + c1x),
987 ny = c1y + 2 * t * (c2y - c1y) + t * t * (p2y - 2 * c2y + c1y),
988 ax = (1 - t) * p1x + t * c1x,
989 ay = (1 - t) * p1y + t * c1y,
990 cx = (1 - t) * c2x + t * p2x,
991 cy = (1 - t) * c2y + t * p2y,
992 alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
993 (mx > nx || my < ny) && (alpha += 180);
994 return {x: x, y: y, m: {x: mx, y: my}, n: {x: nx, y: ny}, start: {x: ax, y: ay}, end: {x: cx, y: cy}, alpha: alpha};
996 var pathDimensions = cacher(function (path) {
998 return {x: 0, y: 0, width: 0, height: 0};
1000 path = path2curve(path);
1006 for (var i = 0, ii = path.length; i < ii; i++) {
1014 var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
1015 X = X[concat](dim.min.x, dim.max.x);
1016 Y = Y[concat](dim.min.y, dim.max.y);
1021 var xmin = mmin[apply](0, X),
1022 ymin = mmin[apply](0, Y);
1026 width: mmax[apply](0, X) - xmin,
1027 height: mmax[apply](0, Y) - ymin
1030 pathClone = function (pathArray) {
1032 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1033 pathArray = R.parsePathString(pathArray);
1035 for (var i = 0, ii = pathArray.length; i < ii; i++) {
1037 for (var j = 0, jj = pathArray[i].length; j < jj; j++) {
1038 res[i][j] = pathArray[i][j];
1041 res.toString = R._path2string;
1044 pathToRelative = cacher(function (pathArray) {
1045 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1046 pathArray = R.parsePathString(pathArray);
1054 if (pathArray[0][0] == "M") {
1055 x = pathArray[0][1];
1056 y = pathArray[0][2];
1060 res.push(["M", x, y]);
1062 for (var i = start, ii = pathArray.length; i < ii; i++) {
1063 var r = res[i] = [],
1065 if (pa[0] != lowerCase.call(pa[0])) {
1066 r[0] = lowerCase.call(pa[0]);
1074 r[6] = +(pa[6] - x).toFixed(3);
1075 r[7] = +(pa[7] - y).toFixed(3);
1078 r[1] = +(pa[1] - y).toFixed(3);
1084 for (var j = 1, jj = pa.length; j < jj; j++) {
1085 r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
1094 for (var k = 0, kk = pa.length; k < kk; k++) {
1098 var len = res[i].length;
1099 switch (res[i][0]) {
1105 x += +res[i][len - 1];
1108 y += +res[i][len - 1];
1111 x += +res[i][len - 2];
1112 y += +res[i][len - 1];
1115 res.toString = R._path2string;
1118 pathToAbsolute = cacher(function (pathArray) {
1119 if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1120 pathArray = R.parsePathString(pathArray);
1128 if (pathArray[0][0] == "M") {
1129 x = +pathArray[0][1];
1130 y = +pathArray[0][2];
1134 res[0] = ["M", x, y];
1136 for (var i = start, ii = pathArray.length; i < ii; i++) {
1137 var r = res[i] = [],
1139 if (pa[0] != upperCase.call(pa[0])) {
1140 r[0] = upperCase.call(pa[0]);
1148 r[6] = +(pa[6] + x);
1149 r[7] = +(pa[7] + y);
1161 for (var j = 1, jj = pa.length; j < jj; j++) {
1162 r[j] = +pa[j] + ((j % 2) ? x : y);
1166 for (var k = 0, kk = pa.length; k < kk; k++) {
1182 mx = res[i][res[i].length - 2];
1183 my = res[i][res[i].length - 1];
1185 x = res[i][res[i].length - 2];
1186 y = res[i][res[i].length - 1];
1189 res.toString = R._path2string;
1191 }, null, pathClone),
1192 l2c = function (x1, y1, x2, y2) {
1193 return [x1, y1, x2, y2, x2, y2];
1195 q2c = function (x1, y1, ax, ay, x2, y2) {
1199 _13 * x1 + _23 * ax,
1200 _13 * y1 + _23 * ay,
1201 _13 * x2 + _23 * ax,
1202 _13 * y2 + _23 * ay,
1207 a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
1208 // for more information of where this math came from visit:
1209 // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1210 var _120 = PI * 120 / 180,
1211 rad = PI / 180 * (+angle || 0),
1214 rotate = cacher(function (x, y, rad) {
1215 var X = x * math.cos(rad) - y * math.sin(rad),
1216 Y = x * math.sin(rad) + y * math.cos(rad);
1217 return {x: X, y: Y};
1220 xy = rotate(x1, y1, -rad);
1223 xy = rotate(x2, y2, -rad);
1226 var cos = math.cos(PI / 180 * angle),
1227 sin = math.sin(PI / 180 * angle),
1230 var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
1238 k = (large_arc_flag == sweep_flag ? -1 : 1) *
1239 math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
1240 cx = k * rx * y / ry + (x1 + x2) / 2,
1241 cy = k * -ry * x / rx + (y1 + y2) / 2,
1242 f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
1243 f2 = math.asin(((y2 - cy) / ry).toFixed(9));
1245 f1 = x1 < cx ? PI - f1 : f1;
1246 f2 = x2 < cx ? PI - f2 : f2;
1247 f1 < 0 && (f1 = PI * 2 + f1);
1248 f2 < 0 && (f2 = PI * 2 + f2);
1249 if (sweep_flag && f1 > f2) {
1252 if (!sweep_flag && f2 > f1) {
1262 if (abs(df) > _120) {
1266 f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
1267 x2 = cx + rx * math.cos(f2);
1268 y2 = cy + ry * math.sin(f2);
1269 res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
1272 var c1 = math.cos(f1),
1276 t = math.tan(df / 4),
1277 hx = 4 / 3 * rx * t,
1278 hy = 4 / 3 * ry * t,
1280 m2 = [x1 + hx * s1, y1 - hy * c1],
1281 m3 = [x2 + hx * s2, y2 - hy * c2],
1283 m2[0] = 2 * m1[0] - m2[0];
1284 m2[1] = 2 * m1[1] - m2[1];
1286 return [m2, m3, m4][concat](res);
1288 res = [m2, m3, m4][concat](res).join().split(",");
1290 for (var i = 0, ii = res.length; i < ii; i++) {
1291 newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
1296 findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1299 x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1300 y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
1303 curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
1304 var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
1305 b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
1307 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
1308 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
1312 abs(t1) > "1e12" && (t1 = .5);
1313 abs(t2) > "1e12" && (t2 = .5);
1314 if (t1 > 0 && t1 < 1) {
1315 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1319 if (t2 > 0 && t2 < 1) {
1320 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1324 a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
1325 b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
1327 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
1328 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
1329 abs(t1) > "1e12" && (t1 = .5);
1330 abs(t2) > "1e12" && (t2 = .5);
1331 if (t1 > 0 && t1 < 1) {
1332 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1336 if (t2 > 0 && t2 < 1) {
1337 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1342 min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
1343 max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
1346 path2curve = cacher(function (path, path2) {
1347 var p = pathToAbsolute(path),
1348 p2 = path2 && pathToAbsolute(path2),
1349 attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1350 attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1351 processPath = function (path, d) {
1354 return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
1356 !(path[0] in {T:1, Q:1}) && (d.qx = d.qy = null);
1363 path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
1366 nx = d.x + (d.x - (d.bx || d.x));
1367 ny = d.y + (d.y - (d.by || d.y));
1368 path = ["C", nx, ny][concat](path.slice(1));
1371 d.qx = d.x + (d.x - (d.qx || d.x));
1372 d.qy = d.y + (d.y - (d.qy || d.y));
1373 path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
1378 path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
1381 path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
1384 path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
1387 path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
1390 path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
1395 fixArc = function (pp, i) {
1396 if (pp[i].length > 7) {
1400 pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
1403 ii = mmax(p.length, p2 && p2.length || 0);
1406 fixM = function (path1, path2, a1, a2, i) {
1407 if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
1408 path2.splice(i, 0, ["M", a2.x, a2.y]);
1413 ii = mmax(p.length, p2 && p2.length || 0);
1416 for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
1417 p[i] = processPath(p[i], attrs);
1419 p2 && (p2[i] = processPath(p2[i], attrs2));
1420 p2 && fixArc(p2, i);
1421 fixM(p, p2, attrs, attrs2, i);
1422 fixM(p2, p, attrs2, attrs, i);
1425 seglen = seg.length,
1426 seg2len = p2 && seg2.length;
1427 attrs.x = seg[seglen - 2];
1428 attrs.y = seg[seglen - 1];
1429 attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
1430 attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
1431 attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
1432 attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
1433 attrs2.x = p2 && seg2[seg2len - 2];
1434 attrs2.y = p2 && seg2[seg2len - 1];
1436 return p2 ? [p, p2] : p;
1437 }, null, pathClone),
1438 parseDots = cacher(function (gradient) {
1440 for (var i = 0, ii = gradient.length; i < ii; i++) {
1442 par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
1443 dot.color = R.getRGB(par[1]);
1444 if (dot.color.error) {
1447 dot.color = dot.color.hex;
1448 par[2] && (dot.offset = par[2] + "%");
1451 for (i = 1, ii = dots.length - 1; i < ii; i++) {
1452 if (!dots[i].offset) {
1453 var start = toFloat(dots[i - 1].offset || 0),
1455 for (var j = i + 1; j < ii; j++) {
1456 if (dots[j].offset) {
1457 end = dots[j].offset;
1466 var d = (end - start) / (j - i + 1);
1467 for (; i < j; i++) {
1469 dots[i].offset = start + "%";
1475 getContainer = function (x, y, w, h) {
1477 container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
1478 if (container == null) {
1481 if (container.tagName) {
1484 container: container,
1485 width: container.style.pixelWidth || container.offsetWidth,
1486 height: container.style.pixelHeight || container.offsetHeight
1489 return {container: container, width: y, height: w};
1492 return {container: 1, x: x, y: y, width: w, height: h};
1494 plugins = function (con, add) {
1496 for (var prop in add) {
1497 if (add[has](prop) && !(prop in con)) {
1498 switch (typeof add[prop]) {
1501 con[prop] = con === that ? f : function () { return f[apply](that, arguments); };
1505 con[prop] = con[prop] || {};
1506 plugins.call(this, con[prop], add[prop]);
1509 con[prop] = add[prop];
1515 tear = function (el, paper) {
1516 el == paper.top && (paper.top = el.prev);
1517 el == paper.bottom && (paper.bottom = el.next);
1518 el.next && (el.next.prev = el.prev);
1519 el.prev && (el.prev.next = el.next);
1521 tofront = function (el, paper) {
1522 if (paper.top === el) {
1527 el.prev = paper.top;
1528 paper.top.next = el;
1531 toback = function (el, paper) {
1532 if (paper.bottom === el) {
1536 el.next = paper.bottom;
1538 paper.bottom.prev = el;
1541 insertafter = function (el, el2, paper) {
1543 el2 == paper.top && (paper.top = el);
1544 el2.next && (el2.next.prev = el);
1549 insertbefore = function (el, el2, paper) {
1551 el2 == paper.bottom && (paper.bottom = el);
1552 el2.prev && (el2.prev.next = el);
1557 removed = function (methodname) {
1558 return function () {
1559 throw new Error("Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object");
1562 extractTransform = function (el, tstr) {
1564 return el._.transform;
1566 tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
1567 var tdata = R.parseTransformString(tstr),
1575 _.transform = tdata || [];
1577 for (var i = 0, ii = tdata.length; i < ii; i++) {
1581 t[0] = Str(t[0]).toLowerCase();
1582 if (t[0] == "t" && tlen == 3) {
1583 m.translate(t[1], t[2]);
1584 } else if (t[0] == "r") {
1586 bb = bb || el.getBBox(1);
1587 m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1589 } else if (tlen == 4) {
1590 m.rotate(t[1], t[2], t[3]);
1593 } else if (t[0] == "s") {
1594 if (tlen == 2 || tlen == 3) {
1595 bb = bb || el.getBBox(1);
1596 m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1599 } else if (tlen == 5) {
1600 m.scale(t[1], t[2], t[3], t[4]);
1604 } else if (t[0] == "m" && tlen == 7) {
1605 m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
1620 if (sx == 1 && sy == 1 && !deg && _.bbox) {
1627 getEmpty = function (item) {
1629 case "t": return ["t", 0, 0];
1630 case "m": return ["m", 1, 0, 0, 1, 0, 0];
1631 case "r": if (item.length == 4) {
1632 return ["r", 0, item[2], item[3]];
1636 case "s": if (item.length == 5) {
1637 return ["s", 1, 1, item[3], item[4]];
1638 } else if (item.length == 3) {
1645 equaliseTransform = function (t1, t2) {
1646 t1 = R.parseTransformString(t1) || [];
1647 t2 = R.parseTransformString(t2) || [];
1648 var maxlength = mmax(t1.length, t2.length),
1653 for (; i < maxlength; i++) {
1654 tt1 = t1[i] || getEmpty(t2[i]);
1655 tt2 = t2[i] || getEmpty(tt1);
1656 if ( (tt1[0] != tt2[0]) ||
1657 (tt1[0] == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
1658 (tt1[0] == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
1664 for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
1665 j in tt1 && (from[i][j] = tt1[j]);
1666 j in tt2 && (to[i][j] = tt2[j]);
1675 * Raphael.pathToRelative
1680 * Converts path to relative form
1682 - pathString (string|array) path string or array of segments
1683 = (array) array of segments.
1685 R.pathToRelative = pathToRelative;
1687 * Raphael.path2curve
1692 * Converts path to a new path where all segments are cubic bezier curves.
1694 - pathString (string|array) path string or array of segments
1695 = (array) array of segments.
1697 R.path2curve = path2curve;
1704 * Returns matrix based on given parameters.
1714 R.matrix = function (a, b, c, d, e, f) {
1715 return new Matrix(a, b, c, d, e, f);
1717 function Matrix(a, b, c, d, e, f) {
1734 var matrixproto = Matrix.prototype;
1735 matrixproto.add = function (a, b, c, d, e, f) {
1736 var out = [[], [], []],
1737 m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
1738 matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
1741 if (a && a instanceof Matrix) {
1742 matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
1745 for (x = 0; x < 3; x++) {
1746 for (y = 0; y < 3; y++) {
1748 for (z = 0; z < 3; z++) {
1749 res += m[x][z] * matrix[z][y];
1761 matrixproto.invert = function () {
1762 var x = a * d - b * c;
1763 return new Matrix(d / x, -b / x, -c / x, a / x, (c * f - d * e) / x, (b * e - a * f) / x);
1765 matrixproto.clone = function () {
1766 return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
1768 matrixproto.translate = function (x, y) {
1769 this.add(1, 0, 0, 1, x, y);
1771 matrixproto.scale = function (x, y, cx, cy) {
1772 y == null && (y = x);
1773 this.add(1, 0, 0, 1, cx, cy);
1774 this.add(x, 0, 0, y, 0, 0);
1775 this.add(1, 0, 0, 1, -cx, -cy);
1777 matrixproto.rotate = function (a, x, y) {
1779 var cos = +math.cos(a).toFixed(9),
1780 sin = +math.sin(a).toFixed(9);
1781 this.add(cos, sin, -sin, cos, x, y);
1782 this.add(1, 0, 0, 1, -x, -y);
1784 matrixproto.x = function (x, y) {
1785 return x * this.a + y * this.c + this.e;
1787 matrixproto.y = function (x, y) {
1788 return x * this.b + y * this.d + this.f;
1790 matrixproto.get = function (i) {
1791 return +this[Str.fromCharCode(97 + i)].toFixed(4);
1793 matrixproto.toString = function () {
1795 "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
1796 [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
1798 matrixproto.toFilter = function () {
1799 return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
1800 ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
1801 ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmedthod='auto expand')";
1803 matrixproto.offset = function () {
1804 return [this.e.toFixed(4), this.f.toFixed(4)];
1809 var xlink = "http://www.w3.org/1999/xlink",
1811 block: "M5,0 0,2.5 5,5z",
1812 classic: "M5,0 0,2.5 5,5 3.5,3 3.5,2z",
1813 diamond: "M2.5,0 5,2.5 2.5,5 0,2.5z",
1814 open: "M6,1 1,3.5 6,6",
1815 oval: "M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"
1818 R.toString = function () {
1819 return "Your browser supports SVG.\nYou are running Rapha\xebl " + this.version;
1821 var $ = function (el, attr) {
1823 if (typeof el == "string") {
1826 for (var key in attr) if (attr[has](key)) {
1827 if (key.substring(0, 6) == "xlink:") {
1828 el.setAttributeNS(xlink, key.substring(6), Str(attr[key]));
1830 el[setAttribute](key, Str(attr[key]));
1834 el = g.doc.createElementNS("http://www.w3.org/2000/svg", el);
1835 el.style && (el.style.webkitTapHighlightColor = "rgba(0,0,0,0)");
1839 thePath = function (pathString, SVG) {
1841 SVG.canvas && SVG.canvas.appendChild(el);
1842 var p = new Element(el, SVG);
1844 setFillAndStroke(p, {fill: "none", stroke: "#000", path: pathString});
1848 rgGrad = /^url\(#(.*)\)$/,
1849 removeGradientFill = function (node, paper) {
1850 var oid = node.getAttribute(fillString);
1851 oid = oid && oid.match(rgGrad);
1852 if (oid && !--gradients[oid[1]]) {
1853 delete gradients[oid[1]];
1854 paper.defs.removeChild(g.doc.getElementById(oid[1]));
1857 addGradientFill = function (element, gradient) {
1858 var type = "linear",
1859 id = element.id + gradient,
1862 SVG = element.paper,
1864 el = g.doc.getElementById(id);
1866 gradient = Str(gradient).replace(radial_gradient, function (all, _fx, _fy) {
1871 var dir = ((fy > .5) * 2 - 1);
1872 pow(fx - .5, 2) + pow(fy - .5, 2) > .25 &&
1873 (fy = math.sqrt(.25 - pow(fx - .5, 2)) * dir + .5) &&
1875 (fy = fy.toFixed(5) - 1e-5 * dir);
1879 gradient = gradient.split(/\s*\-\s*/);
1880 if (type == "linear") {
1881 var angle = gradient.shift();
1882 angle = -toFloat(angle);
1886 var vector = [0, 0, math.cos(R.rad(angle)), math.sin(R.rad(angle))],
1887 max = 1 / (mmax(abs(vector[2]), abs(vector[3])) || 1);
1890 if (vector[2] < 0) {
1891 vector[0] = -vector[2];
1894 if (vector[3] < 0) {
1895 vector[1] = -vector[3];
1899 var dots = parseDots(gradient);
1903 if (element.gradient) {
1904 SVG.defs.removeChild(element.gradient);
1905 delete element.gradient;
1908 el = $(type + "Gradient", {id: id});
1909 element.gradient = el;
1910 $(el, type == "radial" ? {
1918 gradientTransform: element.matrix.invert()
1920 SVG.defs.appendChild(el);
1921 for (var i = 0, ii = dots.length; i < ii; i++) {
1922 el.appendChild($("stop", {
1923 offset: dots[i].offset ? dots[i].offset : i ? "100%" : "0%",
1924 "stop-color": dots[i].color || "#fff"
1929 fill: "url(#" + id + ")",
1938 updatePosition = function (o) {
1939 var bbox = o.getBBox(1);
1940 $(o.pattern, {patternTransform: o.matrix.invert() + " translate(" + bbox.x + "," + bbox.y + ")"});
1942 addArrow = function (o, value, isEnd) {
1943 if (o.type == "path") {
1944 var values = Str(value).toLowerCase().split("-"),
1946 se = isEnd ? "end" : "start",
1949 stroke = attrs["stroke-width"],
1961 switch (values[i]) {
1970 case "wide": h = 5; break;
1971 case "narrow": h = 2; break;
1972 case "long": w = 5; break;
1973 case "short": w = 2; break;
1976 if (type == "open") {
1981 refX = isEnd ? 4 : 1;
1984 stroke: attrs.stroke
1995 o._.arrows.endPath && markerCounter[o._.arrows.endPath]--;
1996 o._.arrows.endMarker && markerCounter[o._.arrows.endMarker]--;
1998 o._.arrows.startPath && markerCounter[o._.arrows.startPath]--;
1999 o._.arrows.startMarker && markerCounter[o._.arrows.startMarker]--;
2004 if (type != "none") {
2005 var pathId = "raphael-marker-" + type,
2006 markerId = "raphael-marker-" + se + type + w + h;
2007 if (!g.doc.getElementById(pathId)) {
2008 p.defs.appendChild($($("path"), {
2009 "stroke-linecap": "round",
2013 markerCounter[pathId] = 1;
2015 markerCounter[pathId]++;
2017 var marker = g.doc.getElementById(markerId),
2020 marker = $($("marker"), {
2029 "xlink:href": "#" + pathId,
2030 transform: (isEnd ? " rotate(180 " + w / 2 + " " + h / 2 + ") " : S) + "scale(" + w / t + "," + h / t + ")",
2031 "stroke-width": 1 / ((w / t + h / t) / 2)
2033 marker.appendChild(use);
2034 p.defs.appendChild(marker);
2035 markerCounter[markerId] = 1;
2037 markerCounter[markerId]++;
2038 use = marker.getElementsByTagName("use")[0];
2041 var delta = dx * (type != "diamond" && type != "oval");
2043 from = o._.arrows.startdx * stroke || 0;
2044 to = R.getTotalLength(attrs.path) - delta * stroke;
2046 from = delta * stroke;
2047 to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0);
2050 attr["marker-" + se] = "url(#" + markerId + ")";
2052 attr.d = Raphael.getSubpath(attrs.path, from, to);
2055 o._.arrows[se + "Path"] = pathId;
2056 o._.arrows[se + "Marker"] = markerId;
2057 o._.arrows[se + "dx"] = delta;
2058 o._.arrows[se + "Type"] = type;
2059 o._.arrows[se + "String"] = value;
2062 from = o._.arrows.startdx * stroke || 0;
2063 to = R.getTotalLength(attrs.path) - from;
2066 to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0);
2068 o._.arrows[se + "Path"] && $(node, {d: Raphael.getSubpath(attrs.path, from, to)});
2069 delete o._.arrows[se + "Path"];
2070 delete o._.arrows[se + "Marker"];
2071 delete o._.arrows[se + "dx"];
2072 delete o._.arrows[se + "Type"];
2073 delete o._.arrows[se + "String"];
2075 for (attr in markerCounter) if (markerCounter[has](attr) && !markerCounter[attr]) {
2076 var item = g.doc.getElementById(attr);
2077 item && item.parentNode.removeChild(item);
2081 setFillAndStroke = function (o, params) {
2088 "-..": [3, 1, 1, 1, 1, 1],
2092 "- .": [4, 3, 1, 3],
2093 "--.": [8, 3, 1, 3],
2094 "--..": [8, 3, 1, 3, 1, 3]
2098 addDashes = function (o, value) {
2099 value = dasharray[lowerCase.call(value)];
2101 var width = o.attrs["stroke-width"] || "1",
2102 butt = {round: width, square: width, butt: 0}[o.attrs["stroke-linecap"] || params["stroke-linecap"]] || 0,
2106 dashes[i] = value[i] * width + ((i % 2) ? 1 : -1) * butt;
2108 $(node, {"stroke-dasharray": dashes.join(",")});
2111 for (var att in params) {
2112 if (params[has](att)) {
2113 if (!availableAttrs[has](att)) {
2116 var value = params[att];
2125 var pn = node.parentNode;
2126 if (lowerCase.call(pn.tagName) != "a") {
2128 pn.insertBefore(hl, node);
2129 hl.appendChild(node);
2132 if (att == "target" && value == "blank") {
2133 pn.setAttributeNS(xlink, "show", "new");
2135 pn.setAttributeNS(xlink, att, value);
2139 node.style.cursor = value;
2148 addArrow(o, value, 1);
2151 var rect = Str(value).split(separator);
2152 if (rect.length == 4) {
2153 o.clip && o.clip.parentNode.parentNode.removeChild(o.clip.parentNode);
2154 var el = $("clipPath"),
2156 el.id = createUUID();
2164 o.paper.defs.appendChild(el);
2165 $(node, {"clip-path": "url(#" + el.id + ")"});
2169 var clip = g.doc.getElementById(node.getAttribute("clip-path").replace(/(^url\(#|\)$)/g, E));
2170 clip && clip.parentNode.removeChild(clip);
2171 $(node, {"clip-path": E});
2176 if (o.type == "path") {
2177 $(node, {d: value ? attrs.path = pathToAbsolute(value) : "M0,0"});
2180 "startString" in o._.arrows && addArrow(o, o._.arrows.startString);
2181 "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
2186 node[setAttribute](att, value);
2196 value = -attrs.x - (attrs.width || 0);
2199 if (att == "rx" && o.type == "rect") {
2203 node[setAttribute](att, value);
2204 o.pattern && updatePosition(o);
2208 node[setAttribute](att, value);
2218 value = -attrs.y - (attrs.height || 0);
2221 if (att == "ry" && o.type == "rect") {
2225 node[setAttribute](att, value);
2226 o.pattern && updatePosition(o);
2230 if (o.type == "rect") {
2231 $(node, {rx: value, ry: value});
2233 node[setAttribute](att, value);
2238 if (o.type == "image") {
2239 node.setAttributeNS(xlink, "href", value);
2242 case "stroke-width":
2243 if (o._.sx != 1 || o._.sy != 1) {
2244 value /= mmax(abs(o._.sx), abs(o._.sy)) || 1;
2246 if (o.paper._vbSize) {
2247 value *= o.paper._vbSize;
2249 node[setAttribute](att, value);
2250 if (attrs["stroke-dasharray"]) {
2251 addDashes(o, attrs["stroke-dasharray"]);
2254 "startString" in o._.arrows && addArrow(o, o._.arrows.startString);
2255 "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
2258 case "stroke-dasharray":
2259 addDashes(o, value);
2262 var isURL = Str(value).match(ISURL);
2265 var ig = $("image");
2266 el.id = createUUID();
2267 $(el, {x: 0, y: 0, patternUnits: "userSpaceOnUse", height: 1, width: 1});
2268 $(ig, {x: 0, y: 0, "xlink:href": isURL[1]});
2272 preload(isURL[1], function () {
2273 var w = this.offsetWidth,
2274 h = this.offsetHeight;
2275 $(el, {width: w, height: h});
2276 $(ig, {width: w, height: h});
2280 o.paper.defs.appendChild(el);
2281 node.style.fill = "url(#" + el.id + ")";
2282 $(node, {fill: "url(#" + el.id + ")"});
2284 o.pattern && updatePosition(o);
2287 var clr = R.getRGB(value);
2289 delete params.gradient;
2290 delete attrs.gradient;
2291 !R.is(attrs.opacity, "undefined") &&
2292 R.is(params.opacity, "undefined") &&
2293 $(node, {opacity: attrs.opacity});
2294 !R.is(attrs["fill-opacity"], "undefined") &&
2295 R.is(params["fill-opacity"], "undefined") &&
2296 $(node, {"fill-opacity": attrs["fill-opacity"]});
2297 } else if ((o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value)) {
2298 if ("opacity" in attrs || "fill-opacity" in attrs) {
2299 var gradient = g.doc.getElementById(node.getAttribute(fillString).replace(/^url\(#|\)$/g, E));
2301 var stops = gradient.getElementsByTagName("stop");
2302 $(stops[stops.length - 1], {"stop-opacity": ("opacity" in attrs ? attrs.opacity : 1) * ("fill-opacity" in attrs ? attrs["fill-opacity"] : 1)});
2305 attrs.gradient = value;
2306 attrs.fill = "none";
2309 clr[has]("opacity") && $(node, {"fill-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity});
2311 clr = R.getRGB(value);
2312 node[setAttribute](att, clr.hex);
2313 att == "stroke" && clr[has]("opacity") && $(node, {"stroke-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity});
2314 if (att == "stroke" && o._.arrows) {
2315 "startString" in o._.arrows && addArrow(o, o._.arrows.startString);
2316 "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
2320 (o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value);
2323 if (attrs.gradient && !attrs[has]("stroke-opacity")) {
2324 $(node, {"stroke-opacity": value > 1 ? value / 100 : value});
2327 case "fill-opacity":
2328 if (attrs.gradient) {
2329 gradient = g.doc.getElementById(node.getAttribute(fillString).replace(/^url\(#|\)$/g, E));
2331 stops = gradient.getElementsByTagName("stop");
2332 $(stops[stops.length - 1], {"stop-opacity": value});
2337 att == "font-size" && (value = toInt(value, 10) + "px");
2338 var cssrule = att.replace(/(\-.)/g, function (w) {
2339 return upperCase.call(w.substring(1));
2341 node.style[cssrule] = value;
2343 node[setAttribute](att, value);
2349 tuneText(o, params);
2352 tuneText = function (el, params) {
2353 if (el.type != "text" || !(params[has]("text") || params[has]("font") || params[has]("font-size") || params[has]("x") || params[has]("y"))) {
2358 fontSize = node.firstChild ? toInt(g.doc.defaultView.getComputedStyle(node.firstChild, E).getPropertyValue("font-size"), 10) : 10;
2360 if (params[has]("text")) {
2361 a.text = params.text;
2362 while (node.firstChild) {
2363 node.removeChild(node.firstChild);
2365 var texts = Str(params.text).split("\n"),
2368 for (var i = 0, ii = texts.length; i < ii; i++) if (texts[i]) {
2370 i && $(tspan, {dy: fontSize * leading, x: a.x});
2371 tspan.appendChild(g.doc.createTextNode(texts[i]));
2372 node.appendChild(tspan);
2376 tspans = node.getElementsByTagName("tspan");
2377 for (i = 0, ii = tspans.length; i < ii; i++) if (i) {
2378 $(tspans[i], {dy: fontSize * leading, x: a.x});
2380 $(tspans[0], {dy: 0});
2383 $(node, {x: a.x, y: a.y});
2385 var bb = el._getBBox(),
2386 dif = a.y - (bb.y + bb.height / 2);
2387 dif && R.is(dif, "finite") && $(tspans[0], {dy: dif});
2389 Element = function (node, svg) {
2394 [ property (object) ]
2396 * Gives you a reference to the DOM object, so you can assign event handlers or just mess around.
2398 | // draw a circle at coordinate 10,10 with radius of 10
2399 | var c = paper.circle(10, 10, 10);
2400 | c.node.onclick = function () {
2401 | c.attr("fill", "red");
2404 this[0] = this.node = node;
2407 [ property (object) ]
2409 * Internal reference to @Raphael object. In case it is not available.
2411 | Raphael.el.red = function () {
2412 | var hsb = this.paper.raphael.rgb2hsb(this.attr("fill"));
2414 | this.attr({fill: this.paper.raphael.hsb2rgb(hsb).hex});
2417 node.raphael = true;
2420 [ property (number) ]
2422 * Unique id of the element. Especially usesful when you want to listen to events of the element,
2423 * because all events are fired in format `<module>.<action>.<id>`. Also useful for @Paper.getById method.
2426 node.raphaelid = this.id;
2427 this.matrix = new Matrix;
2428 this.realPath = null;
2431 [ property (object) ]
2433 * Internal reference to “paper” where object drawn. Mainly for use in plugins and element extensions.
2435 | Raphael.el.cross = function () {
2436 | this.attr({fill: "red"});
2437 | this.paper.path("M10,10L50,50M50,10L10,50")
2438 | .attr({stroke: "red"});
2442 this.attrs = this.attrs || {};
2452 !svg.bottom && (svg.bottom = this);
2455 [ property (object) ]
2457 * Reference to the previous element in the hierarchy.
2459 this.prev = svg.top;
2460 svg.top && (svg.top.next = this);
2464 [ property (object) ]
2466 * Reference to the next element in the hierarchy.
2470 elproto = Element.prototype;
2475 * Adds rotation by given angle around given point to the list of
2476 * transformations of the element.
2478 - deg (number) angle in degrees
2479 - cx (number) #optional x coordinate of the centre of rotation
2480 - cy (number) #optional y coordinate of the centre of rotation
2481 * If cx & cy aren’t specified centre of the shape is used as a point of rotation.
2484 elproto.rotate = function (deg, cx, cy) {
2488 deg = Str(deg).split(separator);
2489 if (deg.length - 1) {
2490 cx = toFloat(deg[1]);
2491 cy = toFloat(deg[2]);
2493 deg = toFloat(deg[0]);
2494 (cy == null) && (cx = cy);
2495 if (cx == null || cy == null) {
2496 var bbox = this.getBBox(1);
2497 cx = bbox.x + bbox.width / 2;
2498 cy = bbox.y + bbox.height / 2;
2500 this.transform(this._.transform.concat([["r", deg, cx, cy]]));
2507 * Adds scale by given amount relative to given point to the list of
2508 * transformations of the element.
2510 - sx (number) horisontal scale amount
2511 - sy (number) vertical scale amount
2512 - cx (number) #optional x coordinate of the centre of scale
2513 - cy (number) #optional y coordinate of the centre of scale
2514 * If cx & cy aren’t specified centre of the shape is used instead.
2517 elproto.scale = function (sx, sy, cx, cy) {
2521 sx = Str(sx).split(separator);
2522 if (sx.length - 1) {
2523 sy = toFloat(sx[1]);
2524 cx = toFloat(sx[2]);
2525 cy = toFloat(sx[3]);
2527 sx = toFloat(sx[0]);
2528 (sy == null) && (sy = sx);
2529 (cy == null) && (cx = cy);
2530 if (cx == null || cy == null) {
2531 var bbox = this.getBBox(1);
2533 cx = cx == null ? bbox.x + bbox.width / 2 : cx;
2534 cy = cy == null ? bbox.y + bbox.height / 2 : cy;
2535 this.transform(this._.transform.concat([["s", sx, sy, cx, cy]]));
2542 * Adds translation by given amount to the list of transformations of the element.
2544 - dx (number) horisontal shift
2545 - dy (number) vertical shift
2548 elproto.translate = function (dx, dy) {
2552 dx = Str(dx).split(separator);
2553 if (dx.length - 1) {
2554 dy = toFloat(dx[1]);
2556 dx = toFloat(dx[0]) || 0;
2558 this.transform(this._.transform.concat([["t", dx, dy]]));
2565 * Adds transformation to the element which is separate to other attributes,
2566 * i.e. translation doesn’t change `x` or `y` of the rectange. The format
2567 * of transformation string is similar to the path string syntax:
2568 | "t100,100r30,100,100s2,2,100,100r45s1.5"
2569 * Each letter is a command. There are four commands: `t` is for translate, `r` is for rotate, `s` is for
2570 * scale and `m` is for matrix.
2572 * So, the example line above could be read like “translate by 100, 100; rotate 30° around 100, 100; scale twice around 100, 100;
2573 * rotate 45° around centre; scale 1.5 times relative to centre”. As you can see rotate and scale commands have origin
2574 * coordinates as optional parameters, the default is the centre point of the element.
2575 * Matrix accepts six parameters.
2577 | var el = paper.rect(10, 20, 300, 200);
2578 | // translate 100, 100, rotate 45°, translate -100, 0
2579 | el.transform("t100,100r45t-100,0");
2580 | // if you want you can append or prepend transformations
2581 | el.transform("...t50,50");
2582 | el.transform("s2...");
2584 | el.transform("t50,50...t-50-50");
2585 | // to reset transformation call method with empty string
2587 | // to get current value call it without parameters
2588 | console.log(el.transform());
2590 - tstr (string) #optional transformation string
2591 * If tstr isn’t specified
2592 = (string) current transformation string
2596 elproto.transform = function (tstr) {
2601 extractTransform(this, tstr);
2603 this.clip && $(this.clip, {transform: this.matrix.invert()});
2604 // this.gradient && $(this.gradient, {gradientTransform: this.matrix.invert()});
2605 this.pattern && updatePosition(this);
2606 this.node && $(this.node, {transform: this.matrix});
2608 if (_.sx != 1 || _.sy != 1) {
2609 var sw = this.attrs[has]("stroke-width") ? this.attrs["stroke-width"] : 1;
2610 this.attr({"stroke-width": sw});
2619 * Makes element invisible. See @Element.show.
2622 elproto.hide = function () {
2623 !this.removed && this.paper.safari(this.node.style.display = "none");
2630 * Makes element visible. See @Element.hide.
2633 elproto.show = function () {
2634 !this.removed && this.paper.safari(this.node.style.display = "");
2641 * Removes element form the paper.
2643 elproto.remove = function () {
2647 eve.unbind("*.*." + this.id);
2648 tear(this, this.paper);
2649 this.node.parentNode.removeChild(this.node);
2650 for (var i in this) {
2653 this.removed = true;
2655 elproto._getBBox = function () {
2656 if (this.node.style.display == "none") {
2662 bbox = this.node.getBBox();
2664 // Firefox 3.0.x plays badly here
2668 hide && this.hide();
2675 * Sets the attributes of the element.
2677 - attrName (string) attribute’s name
2678 - value (string) value
2680 - params (object) object of name/value pairs
2682 - attrName (string) attribute’s name
2684 - attrNames (array) in this case method returns array of current values for given attribute names
2685 = (object) @Element if attrsName & value or params are passed in.
2686 = (...) value of the attribute if only attrsName is passed in.
2687 = (array) array of values of the attribute if attrsNames is passed in.
2688 = (object) object of attributes if nothing is passed in.
2689 > Possible parameters
2690 # <p>Please refer to the <a href="http://www.w3.org/TR/SVG/" title="The W3C Recommendation for the SVG language describes these properties in detail.">SVG specification</a> for an explanation of these parameters.</p>
2691 o arrow-end (string) arrowhead on the end of the path. The format for string is `<type>[-<width>[-<length>]]`. Possible types: `classic`, `block`, `open`, `oval`, `diamond`, `none`, width: `wide`, `narrow`, `midium`, length: `long`, `short`, `midium`.
2692 o clip-rect (string) comma or space separated values: x, y, width and height
2693 o cursor (string) CSS type of the cursor
2696 o fill (string) colour, gradient or image
2697 o fill-opacity (number)
2699 o font-family (string)
2700 o font-size (number) font size in pixels
2701 o font-weight (string)
2703 o href (string) URL, if specified element behaves as hyperlink
2705 o path (string) SVG path string format
2709 o src (string) image URL, only works for @Element.image element
2710 o stroke (string) stroke colour
2711 o stroke-dasharray (string) [“”, “`-`”, “`.`”, “`-.`”, “`-..`”, “`. `”, “`- `”, “`--`”, “`- .`”, “`--.`”, “`--..`”]
2712 o stroke-linecap (string) [“`butt`”, “`square`”, “`round`”]
2713 o stroke-linejoin (string) [“`bevel`”, “`round`”, “`miter`”]
2714 o stroke-miterlimit (number)
2715 o stroke-opacity (number)
2716 o stroke-width (number) stroke width in pixels, default is '1'
2717 o target (string) used with href
2718 o text (string) contents of the text element. Use `\n` for multiline text
2719 o text-anchor (string) [“`start`”, “`middle`”, “`end`”], default is “`middle`”
2720 o title (string) will create tooltip with a given text
2721 o transform (string) see @Element.transform
2726 * Linear gradient format: “`‹angle›-‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`90-#fff-#000`” – 90°
2727 * gradient from white to black or “`0-#fff-#f00:20-#000`” – 0° gradient from white via red (at 20%) to black.
2729 * radial gradient: “`r[(‹fx›, ‹fy›)]‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`r#fff-#000`” –
2730 * gradient from white to black or “`r(0.25, 0.75)#fff-#000`” – gradient from white to black with focus point
2731 * at 0.25, 0.75. Focus point coordinates are in 0..1 range. Radial gradients can only be applied to circles and ellipses.
2733 # <p>Please refer to <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path’s data attribute’s format are described in the SVG specification.">SVG documentation regarding path string</a>. Raphaël fully supports it.</p>
2736 # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
2737 # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
2738 # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
2739 # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
2740 # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
2741 # <li>rgba(•••, •••, •••, •••) — red, green and blue channels’ values: (“<code>rgba(200, 100, 0, .5)</code>”)</li>
2742 # <li>rgba(•••%, •••%, •••%, •••%) — same as above, but in %: (“<code>rgba(100%, 175%, 0%, 50%)</code>”)</li>
2743 # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
2744 # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
2745 # <li>hsba(•••, •••, •••, •••) — same as above, but with opacity</li>
2746 # <li>hsl(•••, •••, •••) — almost the same as hsb, see <a href="http://en.wikipedia.org/wiki/HSL_and_HSV" title="HSL and HSV - Wikipedia, the free encyclopedia">Wikipedia page</a></li>
2747 # <li>hsl(•••%, •••%, •••%) — same as above, but in %</li>
2748 # <li>hsla(•••, •••, •••) — same as above, but with opacity</li>
2749 # <li>Optionally for hsb and hsl you could specify hue as a degree: “<code>hsl(240deg, 1, .5)</code>” or, if you want to go fancy, “<code>hsl(240°, 1, .5)</code>”</li>
2752 elproto.attr = function (name, value) {
2758 for (var i in this.attrs) if (this.attrs[has](i)) {
2759 res[i] = this.attrs[i];
2761 res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
2762 res.transform = this._.transform;
2765 if (value == null && R.is(name, string)) {
2766 if (name == fillString && this.attrs.fill == "none" && this.attrs.gradient) {
2767 return this.attrs.gradient;
2769 if (name == "transform") {
2770 return this._.transform;
2772 if (name in this.attrs) {
2773 return this.attrs[name];
2774 } else if (R.is(this.paper.customAttributes[name], "function")) {
2775 return this.paper.customAttributes[name].def;
2777 return availableAttrs[name];
2780 if (value == null && R.is(name, array)) {
2782 for (var j = 0, jj = name.length; j < jj; j++) {
2783 values[name[j]] = this.attr(name[j]);
2787 if (value != null) {
2789 params[name] = value;
2790 } else if (name != null && R.is(name, "object")) {
2793 for (var key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
2794 var par = this.paper.customAttributes[key].apply(this, [][concat](params[key]));
2795 this.attrs[key] = params[key];
2796 for (var subkey in par) if (par[has](subkey)) {
2797 params[subkey] = par[subkey];
2800 setFillAndStroke(this, params);
2807 * Moves the element so it is the closest to the viewer’s eyes, on top of other elements.
2810 elproto.toFront = function () {
2814 this.node.parentNode.appendChild(this.node);
2815 var svg = this.paper;
2816 svg.top != this && tofront(this, svg);
2823 * Moves the element so it is the furthest from the viewer’s eyes, behind other elements.
2826 elproto.toBack = function () {
2830 if (this.node.parentNode.firstChild != this.node) {
2831 this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild);
2832 toback(this, this.paper);
2833 var svg = this.paper;
2838 * Element.insertAfter
2841 * Inserts current object after the given one.
2844 elproto.insertAfter = function (element) {
2848 var node = element.node || element[element.length - 1].node;
2849 if (node.nextSibling) {
2850 node.parentNode.insertBefore(this.node, node.nextSibling);
2852 node.parentNode.appendChild(this.node);
2854 insertafter(this, element, this.paper);
2858 * Element.insertBefore
2861 * Inserts current object before the given one.
2864 elproto.insertBefore = function (element) {
2868 var node = element.node || element[0].node;
2869 node.parentNode.insertBefore(this.node, node);
2870 insertbefore(this, element, this.paper);
2873 elproto.blur = function (size) {
2874 // Experimental. No Safari support. Use it on your own risk.
2877 var fltr = $("filter"),
2878 blur = $("feGaussianBlur");
2879 t.attrs.blur = size;
2880 fltr.id = createUUID();
2881 $(blur, {stdDeviation: +size || 1.5});
2882 fltr.appendChild(blur);
2883 t.paper.defs.appendChild(fltr);
2885 $(t.node, {filter: "url(#" + fltr.id + ")"});
2888 t._blur.parentNode.removeChild(t._blur);
2890 delete t.attrs.blur;
2892 t.node.removeAttribute("filter");
2895 var theCircle = function (svg, x, y, r) {
2896 var el = $("circle");
2897 svg.canvas && svg.canvas.appendChild(el);
2898 var res = new Element(el, svg);
2899 res.attrs = {cx: x, cy: y, r: r, fill: "none", stroke: "#000"};
2900 res.type = "circle";
2904 theRect = function (svg, x, y, w, h, r) {
2906 svg.canvas && svg.canvas.appendChild(el);
2907 var res = new Element(el, svg);
2908 res.attrs = {x: x, y: y, width: w, height: h, r: r || 0, rx: r || 0, ry: r || 0, fill: "none", stroke: "#000"};
2913 theEllipse = function (svg, x, y, rx, ry) {
2914 var el = $("ellipse");
2915 svg.canvas && svg.canvas.appendChild(el);
2916 var res = new Element(el, svg);
2917 res.attrs = {cx: x, cy: y, rx: rx, ry: ry, fill: "none", stroke: "#000"};
2918 res.type = "ellipse";
2922 theImage = function (svg, src, x, y, w, h) {
2923 var el = $("image");
2924 $(el, {x: x, y: y, width: w, height: h, preserveAspectRatio: "none"});
2925 el.setAttributeNS(xlink, "href", src);
2926 svg.canvas && svg.canvas.appendChild(el);
2927 var res = new Element(el, svg);
2928 res.attrs = {x: x, y: y, width: w, height: h, src: src};
2932 theText = function (svg, x, y, text) {
2934 // $(el, {x: x, y: y, "text-anchor": "middle"});
2935 svg.canvas && svg.canvas.appendChild(el);
2936 var res = new Element(el, svg);
2940 "text-anchor": "middle",
2942 font: availableAttrs.font,
2947 setFillAndStroke(res, res.attrs);
2950 setSize = function (width, height) {
2951 this.width = width || this.width;
2952 this.height = height || this.height;
2953 this.canvas[setAttribute]("width", this.width);
2954 this.canvas[setAttribute]("height", this.height);
2955 if (this._viewBox) {
2956 this.setViewBox.apply(this, this._viewBox);
2960 create = function () {
2961 var con = getContainer[apply](0, arguments),
2962 container = con && con.container,
2966 height = con.height;
2968 throw new Error("SVG container not found.");
2970 var cnvs = $("svg"),
2971 css = "overflow:hidden;",
2975 width = width || 512;
2976 height = height || 342;
2981 xmlns: "http://www.w3.org/2000/svg"
2983 if (container == 1) {
2984 cnvs.style.cssText = css + "position:absolute;left:" + x + "px;top:" + y + "px";
2985 g.doc.body.appendChild(cnvs);
2988 cnvs.style.cssText = css + "position:relative";
2989 if (container.firstChild) {
2990 container.insertBefore(cnvs, container.firstChild);
2992 container.appendChild(cnvs);
2995 container = new Paper;
2996 container.width = width;
2997 container.height = height;
2998 container.canvas = cnvs;
2999 plugins.call(container, container, R.fn);
3001 container._left = container._top = 0;
3002 isFloating && (container.renderfix = fun);
3003 container.renderfix();
3007 setViewBox = function (x, y, w, h, fit) {
3008 eve("setViewBox", this, this._viewBox, [x, y, w, h, fit]);
3009 var size = mmax(w / this.width, h / this.height),
3011 aspectRatio = fit ? "meet" : "xMinYMin",
3018 delete this._vbSize;
3019 vb = "0 0 " + this.width + S + this.height;
3021 this._vbSize = size;
3022 vb = x + S + y + S + w + S + h;
3026 preserveAspectRatio: aspectRatio
3028 while (size && top) {
3029 sw = "stroke-width" in top.attrs ? top.attrs["stroke-width"] : 1;
3030 top.attr({"stroke-width": sw});
3035 this._viewBox = [x, y, w, h, !!fit];
3042 * Fixes the issue of Firefox and IE9 regarding subpixel rendering. If paper is dependant
3043 * on other elements after reflow it could shift half pixel which cause for lines to lost their crispness.
3044 * This method fixes the issue.
3046 Special thanks to Mariusz Nowak (http://www.medikoo.com/) for this method.
3048 paperproto.renderfix = function () {
3049 var cnvs = this.canvas,
3051 pos = cnvs.getScreenCTM(),
3056 this._left = (this._left + left) % 1;
3057 s.left = this._left + "px";
3060 this._top = (this._top + top) % 1;
3061 s.top = this._top + "px";
3069 * Clears the paper, i.e. removes all the elements.
3071 paperproto.clear = function () {
3073 var c = this.canvas;
3074 while (c.firstChild) {
3075 c.removeChild(c.firstChild);
3077 this.bottom = this.top = null;
3078 (this.desc = $("desc")).appendChild(g.doc.createTextNode("Created with Rapha\xebl " + R.version));
3079 c.appendChild(this.desc);
3080 c.appendChild(this.defs = $("defs"));
3086 * Removes the paper from the DOM.
3088 paperproto.remove = function () {
3089 eve("remove", this);
3090 this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas);
3091 for (var i in this) {
3092 this[i] = removed(i);
3099 var map = {M: "m", L: "l", C: "c", Z: "x", m: "t", l: "r", c: "v", z: "x"},
3100 bites = /([clmz]),?([^clmz]*)/gi,
3101 blurregexp = / progid:\S+Blur\([^\)]+\)/g,
3102 val = /-?[^,\s-]+/g,
3103 cssDot = "position:absolute;left:0;top:0;width:1px;height:1px",
3105 pathTypes = {path: 1, rect: 1},
3106 ovalTypes = {circle: 1, ellipse: 1},
3107 path2vml = function (path) {
3108 var total = /[ahqstv]/ig,
3109 command = pathToAbsolute;
3110 Str(path).match(total) && (command = path2curve);
3112 if (command == pathToAbsolute && !Str(path).match(total)) {
3113 var res = Str(path).replace(bites, function (all, command, args) {
3115 isMove = lowerCase.call(command) == "m",
3117 args.replace(val, function (value) {
3118 if (isMove && vals.length == 2) {
3119 res += vals + map[command == "m" ? "l" : "L"];
3122 vals.push(round(value * zoom));
3128 var pa = command(path), p, r;
3130 for (var i = 0, ii = pa.length; i < ii; i++) {
3132 r = lowerCase.call(pa[i][0]);
3133 r == "z" && (r = "x");
3134 for (var j = 1, jj = p.length; j < jj; j++) {
3135 r += round(p[j] * zoom) + (j != jj - 1 ? "," : E);
3141 compensation = function (deg, dx, dy) {
3143 m.rotate(-deg, .5, .5);
3149 setCoords = function (p) {
3156 fillpos = _.fillpos,
3165 s.visibility = "hidden";
3166 o.coordsize = abs(kx) + S + abs(ky);
3167 s.rotation = deg * (sx * sy < 0 ? -1 : 1);
3169 var c = compensation(deg, dx, dy);
3173 sx < 0 && (flip += "x");
3174 sy < 0 && (flip += " y") && (y = -1);
3176 o.coordorigin = (dx * -kx) + S + (dy * -ky);
3177 if (fillpos || _.fillsize) {
3178 var fill = o.getElementsByTagName(fillString);
3179 fill = fill && fill[0];
3180 o.removeChild(fill);
3182 c = compensation(deg, m.x(fillpos[0], fillpos[1]), m.y(fillpos[0], fillpos[1]));
3183 fill.position = c.dx * y + S + c.dy * y;
3186 fill.size = _.fillsize[0] * abs(sx) + S + _.fillsize[1] * abs(sy);
3188 o.appendChild(fill);
3190 s.visibility = "visible";
3192 R.toString = function () {
3193 return "Your browser doesn\u2019t support SVG. Falling down to VML.\nYou are running Rapha\xebl " + this.version;
3195 addArrow = function (o, value, isEnd) {
3196 var values = Str(value).toLowerCase().split("-"),
3197 se = isEnd ? "end" : "start",
3203 switch (values[i]) {
3213 case "narrow": h = values[i]; break;
3215 case "short": w = values[i]; break;
3218 var stroke = o.node.getElementsByTagName("stroke")[0];
3219 stroke[se + "arrow"] = type;
3220 stroke[se + "arrowlength"] = w;
3221 stroke[se + "arrowwidth"] = h;
3223 setFillAndStroke = function (o, params) {
3224 o.paper.canvas.style.display = "none";
3225 o.attrs = o.attrs || {};
3230 newpath = pathTypes[o.type] && (params.x != a.x || params.y != a.y || params.width != a.width || params.height != a.height || params.cx != a.cx || params.cy != a.cy || params.rx != a.rx || params.ry != a.ry || params.r != a.r),
3231 isOval = ovalTypes[o.type] && (a.cx != params.cx || a.cy != params.cy || a.r != params.r || a.rx != params.rx || a.ry != params.ry),
3235 for (var par in params) if (params[has](par)) {
3236 a[par] = params[par];
3239 a.path = getPath[o.type](o);
3242 params.href && (node.href = params.href);
3243 params.title && (node.title = params.title);
3244 params.target && (node.target = params.target);
3245 params.cursor && (s.cursor = params.cursor);
3246 "blur" in params && o.blur(params.blur);
3247 "transform" in params && o.transform(params.transform);
3248 if (params.path && o.type == "path" || newpath) {
3249 node.path = path2vml(a.path);
3254 rx = a.rx || a.r || 0,
3255 ry = a.ry || a.r || 0;
3256 node.path = R.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x", round((cx - rx) * zoom), round((cy - ry) * zoom), round((cx + rx) * zoom), round((cy + ry) * zoom), round(cx * zoom));
3258 if ("clip-rect" in params) {
3259 var rect = Str(params["clip-rect"]).split(separator);
3260 if (rect.length == 4) {
3261 rect[2] = +rect[2] + (+rect[0]);
3262 rect[3] = +rect[3] + (+rect[1]);
3263 var div = node.clipRect || g.doc.createElement("div"),
3265 group = node.parentNode;
3266 dstyle.clip = R.format("rect({1}px {2}px {3}px {0}px)", rect);
3267 if (!node.clipRect) {
3268 dstyle.position = "absolute";
3271 dstyle.width = o.paper.width + "px";
3272 dstyle.height = o.paper.height + "px";
3273 group.parentNode.insertBefore(div, group);
3274 div.appendChild(group);
3275 node.clipRect = div;
3278 if (!params["clip-rect"]) {
3279 node.clipRect && (node.clipRect.style.clip = E);
3283 var textpathStyle = o.textpath.style;
3284 params.font && (textpathStyle.font = params.font);
3285 params["font-family"] && (textpathStyle.fontFamily = '"' + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + '"');
3286 params["font-size"] && (textpathStyle.fontSize = params["font-size"]);
3287 params["font-weight"] && (textpathStyle.fontWeight = params["font-weight"]);
3288 params["font-style"] && (textpathStyle.fontStyle = params["font-style"]);
3290 if ("arrow-start" in params) {
3291 addArrow(res, params["arrow-start"]);
3293 if ("arrow-end" in params) {
3294 addArrow(res, params["arrow-end"], 1);
3296 if (params.opacity != null ||
3297 params["stroke-width"] != null ||
3298 params.fill != null ||
3299 params.src != null ||
3300 params.stroke != null ||
3301 params["stroke-width"] != null ||
3302 params["stroke-opacity"] != null ||
3303 params["fill-opacity"] != null ||
3304 params["stroke-dasharray"] != null ||
3305 params["stroke-miterlimit"] != null ||
3306 params["stroke-linejoin"] != null ||
3307 params["stroke-linecap"] != null) {
3308 var fill = node.getElementsByTagName(fillString),
3310 fill = fill && fill[0];
3311 !fill && (newfill = fill = createNode(fillString));
3312 if (o.type == "image" && params.src) {
3313 fill.src = params.src;
3315 if ("fill-opacity" in params || "opacity" in params) {
3316 var opacity = ((+a["fill-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+R.getRGB(params.fill).o + 1 || 2) - 1);
3317 opacity = mmin(mmax(opacity, 0), 1);
3318 fill.opacity = opacity;
3320 params.fill && (fill.on = true);
3321 if (fill.on == null || params.fill == "none" || params.fill === null) {
3324 if (fill.on && params.fill) {
3325 var isURL = params.fill.match(ISURL);
3327 fill.parentNode == node && node.removeChild(fill);
3329 fill.src = isURL[1];
3331 var bbox = o.getBBox(1);
3332 fill.position = bbox.x + S + bbox.y;
3333 o._.fillpos = [bbox.x, bbox.y];
3335 preload(isURL[1], function () {
3336 o._.fillsize = [this.offsetWidth, this.offsetHeight];
3339 fill.color = R.getRGB(params.fill).hex;
3341 fill.type = "solid";
3342 if (R.getRGB(params.fill).error && (res.type in {circle: 1, ellipse: 1} || Str(params.fill).charAt() != "r") && addGradientFill(res, params.fill, fill)) {
3344 a.gradient = params.fill;
3345 fill.rotate = false;
3349 node.appendChild(fill);
3350 var stroke = (node.getElementsByTagName("stroke") && node.getElementsByTagName("stroke")[0]),
3352 !stroke && (newstroke = stroke = createNode("stroke"));
3353 if ((params.stroke && params.stroke != "none") ||
3354 params["stroke-width"] ||
3355 params["stroke-opacity"] != null ||
3356 params["stroke-dasharray"] ||
3357 params["stroke-miterlimit"] ||
3358 params["stroke-linejoin"] ||
3359 params["stroke-linecap"]) {
3362 (params.stroke == "none" || params.stroke === null || stroke.on == null || params.stroke == 0 || params["stroke-width"] == 0) && (stroke.on = false);
3363 var strokeColor = R.getRGB(params.stroke);
3364 stroke.on && params.stroke && (stroke.color = strokeColor.hex);
3365 opacity = ((+a["stroke-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+strokeColor.o + 1 || 2) - 1);
3366 var width = (toFloat(params["stroke-width"]) || 1) * .75;
3367 opacity = mmin(mmax(opacity, 0), 1);
3368 params["stroke-width"] == null && (width = a["stroke-width"]);
3369 params["stroke-width"] && (stroke.weight = width);
3370 width && width < 1 && (opacity *= width) && (stroke.weight = 1);
3371 stroke.opacity = opacity;
3373 params["stroke-linejoin"] && (stroke.joinstyle = params["stroke-linejoin"] || "miter");
3374 stroke.miterlimit = params["stroke-miterlimit"] || 8;
3375 params["stroke-linecap"] && (stroke.endcap = params["stroke-linecap"] == "butt" ? "flat" : params["stroke-linecap"] == "square" ? "square" : "round");
3376 if (params["stroke-dasharray"]) {
3380 "-.": "shortdashdot",
3381 "-..": "shortdashdotdot",
3386 "--.": "longdashdot",
3387 "--..": "longdashdotdot"
3389 stroke.dashstyle = dasharray[has](params["stroke-dasharray"]) ? dasharray[params["stroke-dasharray"]] : E;
3391 newstroke && node.appendChild(stroke);
3393 if (res.type == "text") {
3394 res.paper.canvas.style.display = E;
3395 var span = res.paper.span,
3397 fontSize = a.font && a.font.match(/\d+(?:\.\d*)?(?=px)/);
3399 a.font && (s.font = a.font);
3400 a["font-family"] && (s.fontFamily = a["font-family"]);
3401 a["font-weight"] && (s.fontWeight = a["font-weight"]);
3402 a["font-style"] && (s.fontStyle = a["font-style"]);
3403 fontSize = toFloat(fontSize ? fontSize[0] : a["font-size"]);
3404 s.fontSize = fontSize * m + "px";
3405 res.textpath.string && (span.innerHTML = Str(res.textpath.string).replace(/</g, "<").replace(/&/g, "&").replace(/\n/g, "<br>"));
3406 var brect = span.getBoundingClientRect();
3407 res.W = a.w = (brect.right - brect.left) / m;
3408 res.H = a.h = (brect.bottom - brect.top) / m;
3409 res.paper.canvas.style.display = "none";
3411 res.Y = a.y + res.H / 2;
3413 ("x" in params || "y" in params) && (res.path.v = R.format("m{0},{1}l{2},{1}", round(a.x * zoom), round(a.y * zoom), round(a.x * zoom) + 1));
3414 var dirtyattrs = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"];
3415 for (var d = 0, dd = dirtyattrs.length; d < dd; d++) if (dirtyattrs[d] in params) {
3420 // text-anchor emulation
3421 switch (a["text-anchor"]) {
3423 res.textpath.style["v-text-align"] = "left";
3424 res.bbx = res.W / 2;
3427 res.textpath.style["v-text-align"] = "right";
3428 res.bbx = -res.W / 2;
3431 res.textpath.style["v-text-align"] = "center";
3435 res.textpath.style["v-text-kern"] = true;
3437 res.paper.canvas.style.display = E;
3439 addGradientFill = function (o, gradient, fill) {
3440 o.attrs = o.attrs || {};
3441 var attrs = o.attrs,
3444 o.attrs.gradient = gradient;
3445 gradient = Str(gradient).replace(radial_gradient, function (all, fx, fy) {
3450 pow(fx - .5, 2) + pow(fy - .5, 2) > .25 && (fy = math.sqrt(.25 - pow(fx - .5, 2)) * ((fy > .5) * 2 - 1) + .5);
3455 gradient = gradient.split(/\s*\-\s*/);
3456 if (type == "linear") {
3457 var angle = gradient.shift();
3458 angle = -toFloat(angle);
3463 var dots = parseDots(gradient);
3467 o = o.shape || o.node;
3469 o.removeChild(fill);
3471 fill.method = "none";
3472 fill.color = dots[0].color;
3473 fill.color2 = dots[dots.length - 1].color;
3475 for (var i = 0, ii = dots.length; i < ii; i++) {
3476 dots[i].offset && clrs.push(dots[i].offset + S + dots[i].color);
3478 fill.colors && (fill.colors.value = clrs.length ? clrs.join() : "0% " + fill.color);
3479 if (type == "radial") {
3480 fill.type = "gradientTitle";
3481 fill.focus = "100%";
3482 fill.focussize = "0 0";
3483 fill.focusposition = fxfy;
3486 // fill.rotate= true;
3487 fill.type = "gradient";
3488 fill.angle = (270 - angle) % 360;
3490 o.appendChild(fill);
3491 // alert(fill.outerHTML);
3495 Element = function (node, vml) {
3496 this[0] = this.node = node;
3497 node.raphael = true;
3499 node.raphaelid = this.id;
3504 this.matrix = new Matrix;
3515 !vml.bottom && (vml.bottom = this);
3516 this.prev = vml.top;
3517 vml.top && (vml.top.next = this);
3521 elproto = Element.prototype;
3522 elproto.transform = function (tstr) {
3524 return this._.transform;
3526 extractTransform(this, tstr);
3527 var matrix = this.matrix.clone(),
3529 matrix.translate(-.5, -.5);
3530 if (this.type == "image") {
3531 if (Str(tstr).indexOf("m") + 1) {
3532 this.node.style.filter = matrix.toFilter();
3533 var bb = this.getBBox(),
3534 bbt = this.getBBox(1),
3535 im = matrix.invert(),
3536 dx = im.x(bb.x, bb.y) - im.x(bbt.x, bbt.y),
3537 dy = im.y(bb.x, bb.y) - im.y(bbt.x, bbt.y);
3538 // skew.offset = dx + S + dy;
3539 // this.node.getElementsByTagName(fillString)[0].position = skew.offset;
3541 this.node.style.filter = E;
3547 // fillpos = _.fillpos,
3549 // matrix = this.matrix;
3550 // fill = o.getElementsByTagName(fillString)[0],
3551 // angle = fill.angle;
3553 this.node.style.filter = E;
3554 skew.matrix = matrix;
3555 skew.offset = matrix.offset();
3558 // angle = R.rad(270 - angle);
3559 // var dx = 100 * math.cos(angle),
3560 // dy = 100 * math.sin(angle),
3561 // zx = matrix.x(0, 0),
3562 // zy = matrix.y(0, 0),
3563 // mx = matrix.x(dx, dy),
3564 // my = matrix.y(dx, dy);
3565 // angle = R.angle(zx, zy, mx, my);
3566 // fill.angle = (270 - angle) % 360;
3571 elproto.rotate = function (deg, cx, cy) {
3578 deg = Str(deg).split(separator);
3579 if (deg.length - 1) {
3580 cx = toFloat(deg[1]);
3581 cy = toFloat(deg[2]);
3583 deg = toFloat(deg[0]);
3584 (cy == null) && (cx = cy);
3585 if (cx == null || cy == null) {
3586 var bbox = this.getBBox(1);
3587 cx = bbox.x + bbox.width / 2;
3588 cy = bbox.y + bbox.height / 2;
3591 this.transform(this._.transform.concat([["r", deg, cx, cy]]));
3594 elproto.translate = function (dx, dy) {
3598 dx = Str(dx).split(separator);
3599 if (dx.length - 1) {
3600 dy = toFloat(dx[1]);
3602 dx = toFloat(dx[0]) || 0;
3605 this._.bbox.x += dx;
3606 this._.bbox.y += dy;
3608 this.transform(this._.transform.concat([["t", dx, dy]]));
3611 elproto.scale = function (sx, sy, cx, cy) {
3615 sx = Str(sx).split(separator);
3616 if (sx.length - 1) {
3617 sy = toFloat(sx[1]);
3618 cx = toFloat(sx[2]);
3619 cy = toFloat(sx[3]);
3620 isNaN(cx) && (cx = null);
3621 isNaN(cy) && (cy = null);
3623 sx = toFloat(sx[0]);
3624 (sy == null) && (sy = sx);
3625 (cy == null) && (cx = cy);
3626 if (cx == null || cy == null) {
3627 var bbox = this.getBBox(1);
3629 cx = cx == null ? bbox.x + bbox.width / 2 : cx;
3630 cy = cy == null ? bbox.y + bbox.height / 2 : cy;
3632 this.transform(this._.transform.concat([["s", sx, sy, cx, cy]]));
3636 elproto.hide = function () {
3637 !this.removed && (this.node.style.display = "none");
3640 elproto.show = function () {
3641 !this.removed && (this.node.style.display = E);
3644 elproto._getBBox = function () {
3648 if (this.type == "text") {
3650 x: this.X + (this.bbx || 0) - this.W / 2,
3656 return pathDimensions(this.attrs.path);
3659 elproto.remove = function () {
3663 eve.unbind("*.*." + this.id);
3664 tear(this, this.paper);
3665 this.node.parentNode.removeChild(this.node);
3666 this.shape && this.shape.parentNode.removeChild(this.shape);
3667 for (var i in this) {
3670 this.removed = true;
3672 elproto.attr = function (name, value) {
3678 for (var i in this.attrs) if (this.attrs[has](i)) {
3679 res[i] = this.attrs[i];
3681 res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
3684 if (value == null && R.is(name, "string")) {
3685 if (name == fillString && this.attrs.fill == "none" && this.attrs.gradient) {
3686 return this.attrs.gradient;
3688 if (name in this.attrs) {
3689 return this.attrs[name];
3690 } else if (R.is(this.paper.customAttributes[name], "function")) {
3691 return this.paper.customAttributes[name].def;
3693 return availableAttrs[name];
3696 if (this.attrs && value == null && R.is(name, array)) {
3697 var ii, values = {};
3698 for (i = 0, ii = name.length; i < ii; i++) {
3699 values[name[i]] = this.attr(name[i]);
3704 if (value != null) {
3706 params[name] = value;
3708 value == null && R.is(name, "object") && (params = name);
3709 for (var key in params) {
3710 eve("attr." + key + "." + this.id, this, params[key]);
3713 for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
3714 var par = this.paper.customAttributes[key].apply(this, [][concat](params[key]));
3715 this.attrs[key] = params[key];
3716 for (var subkey in par) if (par[has](subkey)) {
3717 params[subkey] = par[subkey];
3720 // this.paper.canvas.style.display = "none";
3721 if (params.text && this.type == "text") {
3722 this.textpath.string = params.text;
3724 setFillAndStroke(this, params);
3725 // this.paper.canvas.style.display = E;
3729 elproto.toFront = function () {
3730 !this.removed && this.node.parentNode.appendChild(this.node);
3731 this.paper.top != this && tofront(this, this.paper);
3734 elproto.toBack = function () {
3738 if (this.node.parentNode.firstChild != this.node) {
3739 this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild);
3740 toback(this, this.paper);
3744 elproto.insertAfter = function (element) {
3748 if (element.constructor == Set) {
3749 element = element[element.length - 1];
3751 if (element.node.nextSibling) {
3752 element.node.parentNode.insertBefore(this.node, element.node.nextSibling);
3754 element.node.parentNode.appendChild(this.node);
3756 insertafter(this, element, this.paper);
3759 elproto.insertBefore = function (element) {
3763 if (element.constructor == Set) {
3764 element = element[0];
3766 element.node.parentNode.insertBefore(this.node, element.node);
3767 insertbefore(this, element, this.paper);
3770 elproto.blur = function (size) {
3771 var s = this.node.runtimeStyle,
3773 f = f.replace(blurregexp, E);
3775 this.attrs.blur = size;
3776 s.filter = f + S + ms + ".Blur(pixelradius=" + (+size || 1.5) + ")";
3777 s.margin = R.format("-{0}px 0 0 -{0}px", round(+size || 1.5));
3781 delete this.attrs.blur;
3785 thePath = function (pathString, vml) {
3786 var el = createNode("shape");
3787 el.style.cssText = cssDot;
3788 el.coordsize = zoom + S + zoom;
3789 el.coordorigin = vml.coordorigin;
3790 var p = new Element(el, vml),
3791 attr = {fill: "none", stroke: "#000"};
3792 pathString && (attr.path = pathString);
3796 setFillAndStroke(p, attr);
3797 vml.canvas.appendChild(el);
3798 var skew = createNode("skew");
3800 el.appendChild(skew);
3805 theRect = function (vml, x, y, w, h, r) {
3806 var path = rectPath(x, y, w, h, r),
3807 res = vml.path(path),
3811 res.W = a.width = w;
3812 res.H = a.height = h;
3818 theEllipse = function (vml, x, y, rx, ry) {
3819 var res = vml.path(),
3825 res.type = "ellipse";
3826 setFillAndStroke(res, {
3834 theCircle = function (vml, x, y, r) {
3835 var res = vml.path(),
3839 res.W = res.H = r * 2;
3840 res.type = "circle";
3841 setFillAndStroke(res, {
3848 theImage = function (vml, src, x, y, w, h) {
3849 var path = rectPath(x, y, w, h),
3850 res = vml.path(path).attr({stroke: "none"}),
3853 fill = node.getElementsByTagName(fillString)[0];
3857 res.W = a.width = w;
3858 res.H = a.height = h;
3861 fill.parentNode == node && node.removeChild(fill);
3865 res._.fillpos = [x, y];
3866 res._.fillsize = [w, h];
3867 node.appendChild(fill);
3871 theText = function (vml, x, y, text) {
3872 var el = createNode("shape"),
3873 path = createNode("path"),
3874 o = createNode("textpath");
3878 path.v = R.format("m{0},{1}l{2},{1}", round(x * zoom), round(y * zoom), round(x * zoom) + 1);
3879 path.textpathok = true;
3880 o.string = Str(text);
3882 el.style.cssText = "position:absolute;left:0;top:0;width:1;height:1";
3883 el.coordsize = zoom + S + zoom;
3884 el.coordorigin = "0 0";
3885 var p = new Element(el, vml),
3886 attr = {fill: "#000", stroke: "none", font: availableAttrs.font, text: text};
3891 p.attrs.text = Str(text);
3896 setFillAndStroke(p, attr);
3898 el.appendChild(path);
3899 vml.canvas.appendChild(el);
3900 var skew = createNode("skew");
3902 el.appendChild(skew);
3907 setSize = function (width, height) {
3908 var cs = this.canvas.style;
3910 this.height = height;
3911 width == +width && (width += "px");
3912 height == +height && (height += "px");
3915 cs.clip = "rect(0 " + width + " " + height + " 0)";
3916 if (this._viewBox) {
3917 setViewBox.apply(this, this._viewBox);
3921 setViewBox = function (x, y, w, h, fit) {
3922 eve("setViewBox", this, this._viewBox, [x, y, w, h, fit]);
3923 var width = this.width,
3924 height = this.height,
3925 size = 1e3 * mmax(w / width, h / height),
3930 if (w * H < width) {
3931 x -= (width - w * H) / 2 / H;
3933 if (h * W < height) {
3934 y -= (height - h * W) / 2 / W;
3937 this._viewBox = [x, y, w, h, !!fit];
3938 this.forEach(function (el) {
3939 el.transform("...");
3944 initWin = function (win) {
3945 var doc = win.document;
3946 doc.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
3948 !doc.namespaces.rvml && doc.namespaces.add("rvml", "urn:schemas-microsoft-com:vml");
3949 createNode = function (tagName) {
3950 return doc.createElement('<rvml:' + tagName + ' class="rvml">');
3953 createNode = function (tagName) {
3954 return doc.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">');
3959 create = function () {
3960 var con = getContainer[apply](0, arguments),
3961 container = con.container,
3962 height = con.height,
3968 throw new Error("VML container not found.");
3970 var res = new Paper,
3971 c = res.canvas = g.doc.createElement("div"),
3975 width = width || 512;
3976 height = height || 342;
3978 res.height = height;
3979 width == +width && (width += "px");
3980 height == +height && (height += "px");
3981 res.coordsize = zoom * 1e3 + S + zoom * 1e3;
3982 res.coordorigin = "0 0";
3983 res.span = g.doc.createElement("span");
3984 res.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;";
3985 c.appendChild(res.span);
3986 cs.cssText = R.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden", width, height);
3987 if (container == 1) {
3988 g.doc.body.appendChild(c);
3991 cs.position = "absolute";
3993 if (container.firstChild) {
3994 container.insertBefore(c, container.firstChild);
3996 container.appendChild(c);
3999 plugins.call(res, res, R.fn);
4000 res.renderfix = fun;
4003 paperproto.clear = function () {
4005 this.canvas.innerHTML = E;
4006 this.span = g.doc.createElement("span");
4007 this.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";
4008 this.canvas.appendChild(this.span);
4009 this.bottom = this.top = null;
4011 paperproto.remove = function () {
4012 eve("remove", this);
4013 this.canvas.parentNode.removeChild(this.canvas);
4014 for (var i in this) {
4015 this[i] = removed(i);
4021 // WebKit rendering bug workaround method
4022 var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
4023 if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
4024 (navigator.vendor == "Google Inc." && version && version[1] < 8)) {
4029 * There is an inconvenient rendering bug in Safari (WebKit):
4030 * sometimes the rendering should be forced.
4031 * This method should help with dealing with this bug.
4033 paperproto.safari = function () {
4034 var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
4035 setTimeout(function () {rect.remove();});
4038 paperproto.safari = fun;
4042 var preventDefault = function () {
4043 this.returnValue = false;
4045 preventTouch = function () {
4046 return this.originalEvent.preventDefault();
4048 stopPropagation = function () {
4049 this.cancelBubble = true;
4051 stopTouch = function () {
4052 return this.originalEvent.stopPropagation();
4054 addEvent = (function () {
4055 if (g.doc.addEventListener) {
4056 return function (obj, type, fn, element) {
4057 var realName = supportsTouch && touchMap[type] ? touchMap[type] : type;
4058 var f = function (e) {
4059 if (supportsTouch && touchMap[has](type)) {
4060 for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
4061 if (e.targetTouches[i].target == obj) {
4063 e = e.targetTouches[i];
4064 e.originalEvent = olde;
4065 e.preventDefault = preventTouch;
4066 e.stopPropagation = stopTouch;
4071 return fn.call(element, e);
4073 obj.addEventListener(realName, f, false);
4074 return function () {
4075 obj.removeEventListener(realName, f, false);
4079 } else if (g.doc.attachEvent) {
4080 return function (obj, type, fn, element) {
4081 var f = function (e) {
4082 e = e || g.win.event;
4083 e.preventDefault = e.preventDefault || preventDefault;
4084 e.stopPropagation = e.stopPropagation || stopPropagation;
4085 return fn.call(element, e);
4087 obj.attachEvent("on" + type, f);
4088 var detacher = function () {
4089 obj.detachEvent("on" + type, f);
4097 dragMove = function (e) {
4100 scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
4101 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
4106 if (supportsTouch) {
4107 var i = e.touches.length,
4110 touch = e.touches[i];
4111 if (touch.identifier == dragi.el._drag.id) {
4114 (e.originalEvent ? e.originalEvent : e).preventDefault();
4121 var node = dragi.el.node,
4123 next = node.nextSibling,
4124 parent = node.parentNode,
4125 display = node.style.display;
4126 g.win.opera && parent.removeChild(node);
4127 node.style.display = "none";
4128 o = dragi.el.paper.getElementByPoint(x, y);
4129 node.style.display = display;
4130 g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
4131 o && eve("drag.over." + dragi.el.id, dragi.el, o);
4134 eve("drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
4137 dragUp = function (e) {
4138 R.unmousemove(dragMove).unmouseup(dragUp);
4139 var i = drag.length,
4143 dragi.el._drag = {};
4144 eve("drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
4148 for (var i = events.length; i--;) {
4149 (function (eventName) {
4150 R[eventName] = Element.prototype[eventName] = function (fn, scope) {
4151 if (R.is(fn, "function")) {
4152 this.events = this.events || [];
4153 this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
4157 R["un" + eventName] = Element.prototype["un" + eventName] = function (fn) {
4158 var events = this.events,
4160 while (l--) if (events[l].name == eventName && events[l].f == fn) {
4162 events.splice(l, 1);
4163 !events.length && delete this.events;
4174 * Adds event handlers for hover for the element.
4176 - f_in (function) handler for hover in
4177 - f_out (function) handler for hover out
4178 - icontext (object) #optional context for hover in handler
4179 - ocontext (object) #optional context for hover out handler
4182 elproto.hover = function (f_in, f_out, scope_in, scope_out) {
4183 return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
4189 * Removes event handlers for hover for the element.
4191 - f_in (function) handler for hover in
4192 - f_out (function) handler for hover out
4195 elproto.unhover = function (f_in, f_out) {
4196 return this.unmouseover(f_in).unmouseout(f_out);
4202 * Adds event handlers for drag of the element.
4204 - onmove (function) handler for moving
4205 - onstart (function) handler for drag start
4206 - onend (function) handler for drag end
4207 - mcontext (object) #optional context for moving handler
4208 - scontext (object) #optional context for drag start handler
4209 - econtext (object) #optional context for drag end handler
4210 * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start,
4211 * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element
4212 * `drag.over.<id>` will be fired as well.
4214 * Start event and start handler will be called in specified context or in context of the element with following parameters:
4215 o x (number) x position of the mouse
4216 o y (number) y position of the mouse
4217 o event (object) DOM event object
4218 * Move event and move handler will be called in specified context or in context of the element with following parameters:
4219 o dx (number) shift by x from the start point
4220 o dy (number) shift by y from the start point
4221 o x (number) x position of the mouse
4222 o y (number) y position of the mouse
4223 o event (object) DOM event object
4224 * End event and end handler will be called in specified context or in context of the element with following parameters:
4225 o event (object) DOM event object
4228 elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
4230 (e.originalEvent || e).preventDefault();
4231 var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
4232 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
4233 this._drag.x = e.clientX + scrollX;
4234 this._drag.y = e.clientY + scrollY;
4235 this._drag.id = e.identifier;
4236 !drag.length && R.mousemove(dragMove).mouseup(dragUp);
4237 drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
4238 onstart && eve.on("drag.start." + this.id, onstart);
4239 onmove && eve.on("drag.move." + this.id, onmove);
4240 onend && eve.on("drag.end." + this.id, onend);
4241 eve("drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
4244 this.mousedown(start);
4248 * Element.onDragOver
4251 * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
4253 - f (function) handler for event
4255 elproto.onDragOver = function (f) {
4256 f ? eve.on("drag.over." + this.id, f) : eve.unbind("drag.over." + this.id);
4262 * Removes all drag event handlers from given element.
4264 elproto.undrag = function () {
4265 var i = drag.length;
4266 while (i--) if (drag[i].el == this) {
4267 R.unmousedown(drag[i].start);
4268 drag.splice(i++, 1);
4269 eve.unbind("drag.*." + this.id);
4271 !drag.length && R.unmousemove(dragMove).unmouseup(dragUp);
4281 - x (number) x coordinate of the centre
4282 - y (number) y coordinate of the centre
4284 = (object) Raphaël element object with type “circle”
4287 | var c = paper.circle(50, 50, 40);
4289 paperproto.circle = function (x, y, r) {
4290 return theCircle(this, x || 0, y || 0, r || 0);
4296 * Draws a rectangle.
4300 - x (number) x coordinate of the top left corner
4301 - y (number) y coordinate of the top left corner
4302 - width (number) width
4303 - height (number) height
4304 - r (number) #optional radius for rounded corners, default is 0
4305 = (object) Raphaël element object with type “rect”
4308 | // regular rectangle
4309 | var c = paper.rect(10, 10, 50, 50);
4310 | // rectangle with rounded corners
4311 | var c = paper.rect(40, 40, 50, 50, 10);
4313 paperproto.rect = function (x, y, w, h, r) {
4314 return theRect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
4324 - x (number) x coordinate of the centre
4325 - y (number) y coordinate of the centre
4326 - rx (number) horizontal radius
4327 - ry (number) vertical radius
4328 = (object) Raphaël element object with type “ellipse”
4331 | var c = paper.ellipse(50, 50, 40, 20);
4333 paperproto.ellipse = function (x, y, rx, ry) {
4334 return theEllipse(this, x || 0, y || 0, rx || 0, ry || 0);
4340 * Creates a path element by given path data string.
4344 - pathString (string) path data in SVG path string format.
4345 = (object) Raphaël element object with type “ellipse”
4346 # Details of a path's data attribute's format are described in the <a href="http://www.w3.org/TR/SVG/paths.html#PathData">SVG specification</a>.
4349 | var c = paper.path("M10 10L90 90");
4350 | // draw a diagonal line:
4351 | // move to 10,10, line to 90,90
4353 paperproto.path = function (pathString) {
4354 pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
4355 return thePath(R.format[apply](R, arguments), this);
4361 * Embeds an image into the surface.
4365 - src (string) URI of the source image
4366 - x (number) x coordinate position
4367 - y (number) y coordinate position
4368 - width (number) width of the image
4369 - height (number) height of the image
4370 = (object) Raphaël element object with type “image”
4373 | var c = paper.image("apple.png", 10, 10, 80, 80);
4375 paperproto.image = function (src, x, y, w, h) {
4376 return theImage(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
4382 * Draws a text string. If you need line breaks, put “\n” in the string.
4386 - x (number) x coordinate position
4387 - y (number) y coordinate position
4388 - text (string) The text string to draw
4389 = (object) Raphaël element object with type “text”
4392 | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
4394 paperproto.text = function (x, y, text) {
4395 return theText(this, x || 0, y || 0, Str(text));
4401 * Creates array-like object to keep and operate several elements at once.
4402 * Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
4403 * Sets act as pseudo elements — all methods available to an element can be used on a set.
4404 = (object) array-like object that represents set of elements
4407 | var st = paper.set();
4409 | paper.circle(10, 10, 5),
4410 | paper.circle(30, 10, 5)
4412 | st.attr({fill: "red"});
4414 paperproto.set = function (itemsArray) {
4415 arguments.length > 1 && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
4416 return new Set(itemsArray);
4422 * If you need to change dimensions of the canvas call this method
4426 - width (number) new width of the canvas
4427 - height (number) new height of the canvas
4429 | var st = paper.set();
4431 | paper.circle(10, 10, 5),
4432 | paper.circle(30, 10, 5)
4434 | st.attr({fill: "red"});
4436 paperproto.setSize = setSize;
4441 * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by
4442 * specifying new boundaries.
4447 - x (number) new x position, default is `0`
4448 - y (number) new y position, default is `0`
4449 - w (number) new width of the canvas
4450 - h (number) new height of the canvas
4451 - fit (boolean) `true` if you want graphics to fit into new boundary box
4453 paperproto.setViewBox = setViewBox;
4458 * Points to the topmost element on the paper
4464 * Points to the bottom element on the paper
4466 paperproto.top = paperproto.bottom = null;
4471 * Points to the @Raphael object/function
4473 paperproto.raphael = R;
4474 var getOffset = function (elem) {
4475 var box = elem.getBoundingClientRect(),
4476 doc = elem.ownerDocument,
4478 docElem = doc.documentElement,
4479 clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
4480 top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
4481 left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
4488 * Paper.getElementByPoint
4491 * Returns you topmost element under given point.
4493 = (object) Raphaël element object
4496 - x (number) x coordinate from the top left corner of the window
4497 - y (number) y coordinate from the top left corner of the window
4499 | paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
4501 paperproto.getElementByPoint = function (x, y) {
4504 target = g.doc.elementFromPoint(x, y);
4505 if (g.win.opera && target.tagName == "svg") {
4506 var so = getOffset(svg),
4507 sr = svg.createSVGRect();
4510 sr.width = sr.height = 1;
4511 var hits = svg.getIntersectionList(sr, null);
4513 target = hits[hits.length - 1];
4519 while (target.parentNode && target != svg.parentNode && !target.raphael) {
4520 target = target.parentNode;
4522 target == paper.canvas.parentNode && (target = svg);
4523 target = target && target.raphael ? paper.getById(target.raphaelid) : null;
4530 * Returns you element by its internal ID.
4535 = (object) Raphaël element object
4537 paperproto.getById = function (id) {
4538 var bot = this.bottom;
4551 * Executes given function for each element on the paper
4553 * If callback function returns `false` it will stop loop running.
4557 - callback (function) function to run
4558 - thisArg (object) context object for the callback
4559 = (object) Paper object
4561 paperproto.forEach = function (callback, thisArg) {
4562 var bot = this.bottom;
4564 if (callback.call(thisArg, bot) === false) {
4572 return this.x + S + this.y;
4574 function x_y_w_h() {
4575 return this.x + S + this.y + S + this.width + "\xd7" + this.height;
4581 * Return bounding box for a given element
4585 - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
4586 = (object) Bounding box object:
4588 o x: (number) top left corner x
4589 o y: (number) top left corner y
4590 o width: (number) width
4591 o height: (number) height
4594 elproto.getBBox = function (isWithoutTransform) {
4599 if (isWithoutTransform) {
4600 if (_.dirty || !_.bboxwt) {
4601 this.realPath = getPath[this.type](this);
4602 _.bboxwt = pathDimensions(this.realPath);
4603 _.bboxwt.toString = x_y_w_h;
4608 if (_.dirty || _.dirtyT || !_.bbox) {
4609 if (_.dirty || !this.realPath) {
4611 this.realPath = getPath[this.type](this);
4613 _.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
4614 _.bbox.toString = x_y_w_h;
4615 _.dirty = _.dirtyT = 0;
4623 = (object) clone of a given element
4626 elproto.clone = function () {
4630 return this.paper[this.type]().attr(this.attr());
4636 * Return set of elements that create glow-like effect around given element. See @Paper.set.
4638 * Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
4642 - glow (object) #optional parameters object with all properties optional:
4644 o width (number) size of the glow, default is `10`
4645 o fill (boolean) will it be filled, default is `false`
4646 o opacity: opacity, default is `0.5`
4647 o offsetx: horizontal offset, default is `0`
4648 o offsety: vertical offset, default is `0`
4649 o color: glow colour, default is `black`
4651 = (object) @Paper.set of elements that represents glow
4653 elproto.glow = function (glow) {
4654 if (this.type == "text") {
4659 width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
4660 fill: glow.fill || false,
4661 opacity: glow.opacity || .5,
4662 offsetx: glow.offsetx || 0,
4663 offsety: glow.offsety || 0,
4664 color: glow.color || "#000"
4669 path = this.realPath || getPath[this.type](this);
4670 path = this.matrix ? mapPath(path, this.matrix) : path;
4671 for (var i = 1; i < c + 1; i++) {
4672 out.push(r.path(path).attr({
4674 fill: s.fill ? s.color : "none",
4675 "stroke-linejoin": "round",
4676 "stroke-linecap": "round",
4677 "stroke-width": +(s.width / c * i).toFixed(3),
4678 opacity: +(s.opacity / c).toFixed(3)
4681 return out.insertBefore(this).translate(s.offsetx, s.offsety);
4683 var curveslengths = {},
4684 getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
4687 name = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y].join(),
4688 cache = curveslengths[name],
4690 !cache && (curveslengths[name] = cache = {data: []});
4691 cache.timer && clearTimeout(cache.timer);
4692 cache.timer = setTimeout(function () {delete curveslengths[name];}, 2e3);
4693 if (length != null && !cache.precision) {
4694 var total = getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
4695 cache.precision = ~~total * 10;
4698 precision = cache.precision || precision;
4699 for (var i = 0; i < precision + 1; i++) {
4700 if (cache.data[i * precision]) {
4701 dot = cache.data[i * precision];
4703 dot = R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, i / precision);
4704 cache.data[i * precision] = dot;
4706 i && (len += pow(pow(old.x - dot.x, 2) + pow(old.y - dot.y, 2), .5));
4707 if (length != null && len >= length) {
4712 if (length == null) {
4716 getLengthFactory = function (istotal, subpath) {
4717 return function (path, length, onlystart) {
4718 path = path2curve(path);
4719 var x, y, p, l, sp = "", subpaths = {}, point,
4721 for (var i = 0, ii = path.length; i < ii; i++) {
4727 l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
4728 if (len + l > length) {
4729 if (subpath && !subpaths.start) {
4730 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
4731 sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
4732 if (onlystart) {return sp;}
4733 subpaths.start = sp;
4734 sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
4740 if (!istotal && !subpath) {
4741 point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
4742 return {x: point.x, y: point.y, alpha: point.alpha};
4749 sp += p.shift() + p;
4752 point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[1], p[2], p[3], p[4], p[5], p[6], 1);
4753 point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
4757 var getTotalLength = getLengthFactory(1),
4758 getPointAtLength = getLengthFactory(),
4759 getSubpathsAtLength = getLengthFactory(0, 1);
4761 * Raphael.getTotalLength
4764 * Returns length of the given path in pixels.
4768 - path (string) SVG path string.
4772 R.getTotalLength = getTotalLength;
4774 * Raphael.getPointAtLength
4777 * Return coordinates of the point located at the given length on the given path.
4781 - path (string) SVG path string
4784 = (object) representation of the point:
4786 o x: (number) x coordinate
4787 o y: (number) y coordinate
4788 o alpha: (number) angle of derivative
4791 R.getPointAtLength = getPointAtLength;
4793 * Raphael.getSubpath
4796 * Return subpath of a given path from given length to given length.
4800 - path (string) SVG path string
4801 - from (number) position of the start of the segment
4802 - to (number) position of the end of the segment
4804 = (string) pathstring for the segment
4806 R.getSubpath = function (path, from, to) {
4807 if (abs(this.getTotalLength(path) - to) < 1e-6) {
4808 return getSubpathsAtLength(path, from).end;
4810 var a = getSubpathsAtLength(path, to, 1);
4811 return from ? getSubpathsAtLength(a, from).end : a;
4814 * Element.getTotalLength
4817 * Returns length of the path in pixels. Only works for element of “path” type.
4820 elproto.getTotalLength = function () {
4821 if (this.type != "path") {return;}
4822 if (this.node.getTotalLength) {
4823 return this.node.getTotalLength();
4825 return getTotalLength(this.attrs.path);
4828 * Element.getPointAtLength
4831 * Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
4837 = (object) representation of the point:
4839 o x: (number) x coordinate
4840 o y: (number) y coordinate
4841 o alpha: (number) angle of derivative
4844 elproto.getPointAtLength = function (length) {
4845 if (this.type != "path") {return;}
4846 return getPointAtLength(this.attrs.path, length);
4849 * Element.getSubpath
4852 * Return subpath of a given element from given length to given length. Only works for element of “path” type.
4856 - from (number) position of the start of the segment
4857 - to (number) position of the end of the segment
4859 = (string) pathstring for the segment
4861 elproto.getSubpath = function (from, to) {
4862 if (this.type != "path") {return;}
4863 return R.getSubpath(this.attrs.path, from, to);
4866 * Raphael.easing_formulas
4869 * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
4872 # <li>“<” or “easeIn” or “ease-in”</li>
4873 # <li>“>” or “easeOut” or “ease-out”</li>
4874 # <li>“<>” or “easeInOut” or “ease-in-out”</li>
4875 # <li>“backIn” or “back-in”</li>
4876 # <li>“backOut” or “back-out”</li>
4877 # <li>“elastic”</li>
4880 # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
4882 var ef = R.easing_formulas = {
4883 linear: function (n) {
4892 "<>": function (n) {
4893 var q = .48 - n / 1.04,
4894 Q = math.sqrt(.1734 + q * q),
4896 X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
4898 Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
4900 return (1 - t) * 3 * t * t + t * t * t;
4902 backIn: function (n) {
4904 return n * n * ((s + 1) * n - s);
4906 backOut: function (n) {
4909 return n * n * ((s + 1) * n + s) + 1;
4911 elastic: function (n) {
4915 return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
4917 bounce: function (n) {
4926 l = s * n * n + .75;
4928 if (n < (2.5 / p)) {
4930 l = s * n * n + .9375;
4933 l = s * n * n + .984375;
4940 ef.easeIn = ef["ease-in"] = ef["<"];
4941 ef.easeOut = ef["ease-out"] = ef[">"];
4942 ef.easeInOut = ef["ease-in-out"] = ef["<>"];
4943 ef["back-in"] = ef.backIn;
4944 ef["back-out"] = ef.backOut;
4946 var animationElements = [],
4947 requestAnimFrame = window.requestAnimationFrame ||
4948 window.webkitRequestAnimationFrame ||
4949 window.mozRequestAnimationFrame ||
4950 window.oRequestAnimationFrame ||
4951 window.msRequestAnimationFrame ||
4952 function (callback) {
4953 setTimeout(callback, 16);
4955 animation = function () {
4956 var Now = +new Date,
4958 for (; l < animationElements.length; l++) {
4959 var e = animationElements[l];
4960 if (e.el.removed || e.paused) {
4963 var time = Now - e.start,
4974 time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
4975 e.status = e.initstatus;
4976 delete e.initstatus;
4977 e.stop && animationElements.splice(l--, 1);
4979 e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
4985 var pos = easing(time / ms);
4986 for (var attr in from) if (from[has](attr)) {
4987 switch (availableAnimAttrs[attr]) {
4989 now = +from[attr] + pos * ms * diff[attr];
4993 upto255(round(from[attr].r + pos * ms * diff[attr].r)),
4994 upto255(round(from[attr].g + pos * ms * diff[attr].g)),
4995 upto255(round(from[attr].b + pos * ms * diff[attr].b))
5000 for (var i = 0, ii = from[attr].length; i < ii; i++) {
5001 now[i] = [from[attr][i][0]];
5002 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
5003 now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
5005 now[i] = now[i].join(S);
5010 if (diff[attr].real) {
5012 for (i = 0, ii = from[attr].length; i < ii; i++) {
5013 now[i] = [from[attr][i][0]];
5014 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
5015 now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
5019 var get = function (i) {
5020 return +from[attr][i] + pos * ms * diff[attr][i];
5022 // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
5023 now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
5027 if (attr == "clip-rect") {
5031 now[i] = +from[attr][i] + pos * ms * diff[attr][i];
5036 var from2 = [].concat(from[attr]);
5038 i = that.paper.customAttributes[attr].length;
5040 now[i] = +from2[i] + pos * ms * diff[attr][i];
5047 (function (id, that, anim) {
5048 setTimeout(function () {
5049 eve("anim.frame." + id, that, anim);
5051 })(that.id, that, e.anim);
5053 (function(f, el, a) {
5054 setTimeout(function() {
5055 eve("anim.finish." + el.id, el, a);
5056 R.is(f, "function") && f.call(el);
5058 })(e.callback, that, e.anim);
5059 console.log(e.repeat);
5061 that.attr(e.origin);
5065 animationElements.splice(l--, 1);
5067 if (e.next && !e.stop) {
5068 runAnimation(e.anim, e.el, e.next, null, e.totalOrigin);
5072 R.svg && that && that.paper && that.paper.safari();
5073 animationElements.length && requestAnimFrame(animation);
5075 upto255 = function (color) {
5076 return mmax(mmin(color, 255), 0);
5079 * Element.animateWith
5082 * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
5086 - params (object) final attributes for the element, see also @Element.attr
5087 - ms (number) number of milliseconds for animation to run
5088 - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
5089 - callback (function) #optional callback function. Will be called at the end of animation.
5091 - animation (object) animation object, see @Raphael.animation
5093 = (object) original element
5095 elproto.animateWith = function (element, params, ms, easing, callback) {
5096 this.animate(params, ms, easing, callback);
5098 for (var i = 0, ii = animationElements.length; i < ii; i++) {
5099 el = animationElements[i];
5100 if (el.el.id == element.id) {
5101 start = el.timestamp;
5102 } else if (el.el.id == this.id) {
5106 return this.animate(params, ms, easing, callback);
5108 function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
5110 bx = 3 * (p2x - p1x) - cx,
5113 by = 3 * (p2y - p1y) - cy,
5115 function sampleCurveX(t) {
5116 return ((ax * t + bx) * t + cx) * t;
5118 function solve(x, epsilon) {
5119 var t = solveCurveX(x, epsilon);
5120 return ((ay * t + by) * t + cy) * t;
5122 function solveCurveX(x, epsilon) {
5123 var t0, t1, t2, x2, d2, i;
5124 for(t2 = x, i = 0; i < 8; i++) {
5125 x2 = sampleCurveX(t2) - x;
5126 if (abs(x2) < epsilon) {
5129 d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
5130 if (abs(d2) < 1e-6) {
5145 x2 = sampleCurveX(t2);
5146 if (abs(x2 - x) < epsilon) {
5154 t2 = (t1 - t0) / 2 + t0;
5158 return solve(t, 1 / (200 * duration));
5160 elproto.onAnimation = function (f) {
5161 f ? eve.on("anim.frame." + this.id, f) : eve.unbind("anim.frame." + this.id);
5164 function Animation(anim, ms) {
5170 for (var attr in this.anim) if (this.anim[has](attr)) {
5171 percents.push(+attr);
5173 percents.sort(sortByNumber);
5175 this.top = percents[percents.length - 1];
5176 this.percents = percents;
5182 * Creates a copy of existing animation object with given delay.
5186 - delay (number) number of ms to pass between animation start and actual animation
5188 = (object) new altered Animation object
5190 Animation.prototype.delay = function (delay) {
5191 var a = new Animation(this.anim, this.ms);
5192 a.times = this.times;
5193 a.del = +delay || 0;
5200 * Creates a copy of existing animation object with given repetition.
5204 - repeat (number) number iterations of animation. For infinite animation pass `Infinity`
5206 = (object) new altered Animation object
5208 Animation.prototype.repeat = function (times) {
5209 var a = new Animation(this.anim, this.ms);
5211 a.times = math.floor(mmax(times, 0)) || 1;
5214 function runAnimation(anim, element, percent, status, totalOrigin) {
5215 percent = toFloat(percent);
5228 for (i = 0, ii = animationElements.length; i < ii; i++) {
5229 var e = animationElements[i];
5230 if (e.el.id == element.id && e.anim == anim) {
5231 if (e.percent != percent) {
5232 animationElements.splice(i, 1);
5237 element.attr(e.totalOrigin);
5242 status = +to; // NaN
5244 for (var i = 0, ii = anim.percents.length; i < ii; i++) {
5245 if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
5246 percent = anim.percents[i];
5247 prev = anim.percents[i - 1] || 0;
5248 ms = ms / anim.top * (percent - prev);
5249 next = anim.percents[i + 1];
5250 params = anim.anim[percent];
5252 } else if (status) {
5253 element.attr(anim.anim[anim.percents[i]]);
5260 for (attr in params) if (params[has](attr)) {
5261 if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
5262 from[attr] = element.attr(attr);
5263 (from[attr] == null) && (from[attr] = availableAttrs[attr]);
5264 to[attr] = params[attr];
5265 switch (availableAnimAttrs[attr]) {
5267 diff[attr] = (to[attr] - from[attr]) / ms;
5270 from[attr] = R.getRGB(from[attr]);
5271 var toColour = R.getRGB(to[attr]);
5273 r: (toColour.r - from[attr].r) / ms,
5274 g: (toColour.g - from[attr].g) / ms,
5275 b: (toColour.b - from[attr].b) / ms
5279 var pathes = path2curve(from[attr], to[attr]),
5281 from[attr] = pathes[0];
5283 for (i = 0, ii = from[attr].length; i < ii; i++) {
5284 diff[attr][i] = [0];
5285 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
5286 diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
5292 eq = equaliseTransform(_[attr], to[attr]);
5294 from[attr] = eq.from;
5297 diff[attr].real = true;
5298 for (i = 0, ii = from[attr].length; i < ii; i++) {
5299 diff[attr][i] = [from[attr][i][0]];
5300 for (j = 1, jj = from[attr][i].length; j < jj; j++) {
5301 diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
5305 var m = (element.matrix || new Matrix).m,
5306 to2 = {_:{transform: _.transform}, getBBox: function () { return element.getBBox(); }};
5315 extractTransform(to2, to[attr]);
5316 to[attr] = to2._.transform;
5318 (to2.matrix.m[0][0] - m[0][0]) / ms,
5319 (to2.matrix.m[1][0] - m[1][0]) / ms,
5320 (to2.matrix.m[0][1] - m[0][1]) / ms,
5321 (to2.matrix.m[1][1] - m[1][1]) / ms,
5322 (to2.matrix.m[0][2] - m[0][2]) / ms,
5323 (to2.matrix.m[1][2] - m[1][2]) / ms
5325 // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
5326 // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
5327 // extractTransform(to2, to[attr]);
5329 // (to2._.sx - _.sx) / ms,
5330 // (to2._.sy - _.sy) / ms,
5331 // (to2._.deg - _.deg) / ms,
5332 // (to2._.dx - _.dx) / ms,
5333 // (to2._.dy - _.dy) / ms
5338 var values = Str(params[attr]).split(separator),
5339 from2 = Str(from[attr]).split(separator);
5340 if (attr == "clip-rect") {
5345 diff[attr][i] = (values[i] - from[attr][i]) / ms;
5351 values = [].concat(params[attr]);
5352 from2 = [].concat(from[attr]);
5354 i = element.paper.customAttributes[attr].length;
5356 diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
5362 var easing = params.easing,
5363 easyeasy = R.easing_formulas[easing];
5365 easyeasy = Str(easing).match(bezierrg);
5366 if (easyeasy && easyeasy.length == 5) {
5367 var curve = easyeasy;
5368 easyeasy = function (t) {
5369 return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
5375 timestamp = params.start || anim.start || +new Date;
5379 timestamp: timestamp,
5380 start: timestamp + (anim.del || 0),
5382 initstatus: status || 0,
5390 callback: params.callback,
5394 origin: element.attr(),
5395 totalOrigin: totalOrigin
5397 animationElements.push(e);
5398 if (status && !isInAnim) {
5400 e.start = new Date - ms * status;
5401 if (animationElements.length == 1) {
5405 animationElements.length == 1 && requestAnimFrame(animation);
5407 isInAnim.initstatus = status;
5408 isInAnim.start = new Date - isInAnim.ms * status;
5410 eve("anim.start." + element.id, element, anim);
5416 * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
5417 * See also @Animation.delay and @Animation.repeat methods.
5421 - params (object) final attributes for the element, see also @Element.attr
5422 - ms (number) number of milliseconds for animation to run
5423 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
5424 - callback (function) #optional callback function. Will be called at the end of animation.
5426 = (object) @Animation
5428 R.animation = function (params, ms, easing, callback) {
5429 if (R.is(easing, "function") || !easing) {
5430 callback = callback || easing || null;
5433 params = Object(params);
5438 for (attr in params) if (params[has](attr) && toFloat(attr) != attr) {
5440 p[attr] = params[attr];
5443 return new Animation(params, ms);
5445 easing && (p.easing = easing);
5446 callback && (p.callback = callback);
5447 return new Animation({100: p}, ms);
5454 * Creates and starts animation for given element.
5458 - params (object) final attributes for the element, see also @Element.attr
5459 - ms (number) number of milliseconds for animation to run
5460 - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
5461 - callback (function) #optional callback function. Will be called at the end of animation.
5463 - animation (object) animation object, see @Raphael.animation
5465 = (object) original element
5467 elproto.animate = function (params, ms, easing, callback) {
5469 if (element.removed) {
5470 callback && callback.call(element);
5473 var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
5474 runAnimation(anim, element, anim.percents[0], null, element.attr());
5481 * Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
5485 - anim (object) animation object
5486 - value (number) number of milliseconds from the beginning of the animation
5488 = (object) original element if `value` is specified
5489 * Note, that during animation following events are triggered:
5491 * On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
5493 elproto.setTime = function (anim, value) {
5494 if (anim && value != null) {
5495 this.status(anim, mmin(value, anim.ms) / anim.ms);
5503 * Gets or sets the status of animation of the element.
5507 - anim (object) #optional animation object
5508 - value (number) #optional 0 – 1. If specified, method works like a setter and sets the status of a given animation to the value. This will cause animation to jump to the given position.
5512 = (array) status if `anim` is not specified. Array of objects in format:
5514 o anim: (object) animation object
5515 o status: (number) status
5518 = (object) original element if `value` is specified
5520 elproto.status = function (anim, value) {
5525 if (value != null) {
5526 runAnimation(anim, this, -1, mmin(value, 1));
5529 len = animationElements.length;
5530 for (; i < len; i++) {
5531 e = animationElements[i];
5532 if (e.el.id == this.id && (!anim || e.anim == anim)) {
5536 out.push({anim: e.anim, status: e.status});
5549 * Stops animation of the element with ability to resume it later on.
5553 - anim (object) #optional animation object
5555 = (object) original element
5557 elproto.pause = function (anim) {
5558 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
5559 if (eve("anim.pause." + this.id, this, animationElements[i].anim) !== false) {
5560 animationElements[i].paused = true;
5569 * Resumes animation if it was paused with @Element.pause method.
5573 - anim (object) #optional animation object
5575 = (object) original element
5577 elproto.resume = function (anim) {
5578 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
5579 var e = animationElements[i];
5580 if (eve("anim.resume." + this.id, this, e.anim) !== false) {
5582 this.status(e.anim, e.status);
5591 * Stops animation of the element.
5595 - anim (object) #optional animation object
5597 = (object) original element
5599 elproto.stop = function (anim) {
5600 for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
5601 if (eve("anim.stop." + this.id, this, animationElements[i].anim) !== false) {
5602 animationElements.splice(i--, 1);
5607 elproto.toString = function () {
5608 return "Rapha\xebl\u2019s object";
5612 var Set = function (items) {
5617 for (var i = 0, ii = items.length; i < ii; i++) {
5618 if (items[i] && (items[i].constructor == Element || items[i].constructor == Set)) {
5619 this[this.items.length] = this.items[this.items.length] = items[i];
5625 setproto = Set.prototype;
5630 * Adds each argument to the current set.
5631 = (object) original element
5633 setproto.push = function () {
5636 for (var i = 0, ii = arguments.length; i < ii; i++) {
5637 item = arguments[i];
5638 if (item && (item.constructor == Element || item.constructor == Set)) {
5639 len = this.items.length;
5640 this[len] = this.items[len] = item;
5650 * Removes last element and returns it.
5653 setproto.pop = function () {
5654 this.length && delete this[this.length--];
5655 return this.items.pop();
5661 * Executes given function for each element in the set.
5663 * If function returns `false` it will stop loop running.
5667 - callback (function) function to run
5668 - thisArg (object) context object for the callback
5669 = (object) Set object
5671 setproto.forEach = function (callback, thisArg) {
5672 for (var i = 0, ii = this.items.length; i < ii; i++) {
5673 if (callback.call(thisArg, this.items[i]) === false) {
5679 for (var method in elproto) if (elproto[has](method)) {
5680 setproto[method] = (function (methodname) {
5681 return function () {
5682 var arg = arguments;
5683 return this.forEach(function (el) {
5684 el[methodname][apply](el, arg);
5689 setproto.attr = function (name, value) {
5690 if (name && R.is(name, array) && R.is(name[0], "object")) {
5691 for (var j = 0, jj = name.length; j < jj; j++) {
5692 this.items[j].attr(name[j]);
5695 for (var i = 0, ii = this.items.length; i < ii; i++) {
5696 this.items[i].attr(name, value);
5701 setproto.animate = function (params, ms, easing, callback) {
5702 (R.is(easing, "function") || !easing) && (callback = easing || null);
5703 var len = this.items.length,
5708 callback && (collector = function () {
5709 !--len && callback.call(set);
5711 easing = R.is(easing, string) ? easing : collector;
5712 var anim = params instanceof Animation ? params : R.animation(params, ms, easing, collector);
5713 item = this.items[--i].animate(anim);
5715 this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim);
5719 setproto.insertAfter = function (el) {
5720 var i = this.items.length;
5722 this.items[i].insertAfter(el);
5726 setproto.getBBox = function () {
5731 for (var i = this.items.length; i--;) if (!this.items[i].removed) {
5732 var box = this.items[i].getBBox();
5735 w.push(box.x + box.width);
5736 h.push(box.y + box.height);
5738 x = mmin[apply](0, x);
5739 y = mmin[apply](0, y);
5743 width: mmax[apply](0, w) - x,
5744 height: mmax[apply](0, h) - y
5747 setproto.clone = function (s) {
5749 for (var i = 0, ii = this.items.length; i < ii; i++) {
5750 s.push(this.items[i].clone());
5754 setproto.toString = function () {
5755 return "Rapha\xebl\u2018s set";
5758 R.registerFont = function (font) {
5762 this.fonts = this.fonts || {};
5768 family = font.face["font-family"];
5769 for (var prop in font.face) if (font.face[has](prop)) {
5770 fontcopy.face[prop] = font.face[prop];
5772 if (this.fonts[family]) {
5773 this.fonts[family].push(fontcopy);
5775 this.fonts[family] = [fontcopy];
5778 fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
5779 for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
5780 var path = font.glyphs[glyph];
5781 fontcopy.glyphs[glyph] = {
5784 d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
5785 return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
5789 for (var k in path.k) if (path[has](k)) {
5790 fontcopy.glyphs[glyph].k[k] = path.k[k];
5797 paperproto.getFont = function (family, weight, style, stretch) {
5798 stretch = stretch || "normal";
5799 style = style || "normal";
5800 weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
5804 var font = R.fonts[family];
5806 var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
5807 for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
5808 if (name.test(fontName)) {
5809 font = R.fonts[fontName];
5816 for (var i = 0, ii = font.length; i < ii; i++) {
5818 if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
5825 paperproto.print = function (x, y, string, font, size, origin, letter_spacing) {
5826 origin = origin || "middle"; // baseline|middle
5827 letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
5828 var out = this.set(),
5829 letters = Str(string).split(E),
5833 R.is(font, string) && (font = this.getFont(font));
5835 scale = (size || 16) / font.face["units-per-em"];
5836 var bb = font.face.bbox.split(separator),
5838 height = +bb[1] + (origin == "baseline" ? bb[3] - bb[1] + (+font.face.descent) : (bb[3] - bb[1]) / 2);
5839 for (var i = 0, ii = letters.length; i < ii; i++) {
5840 var prev = i && font.glyphs[letters[i - 1]] || {},
5841 curr = font.glyphs[letters[i]];
5842 shift += i ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
5843 curr && curr.d && out.push(this.path(curr.d).attr({fill: "#000", stroke: "none", transform: [["t", shift, 0]]}));
5845 out.scale(scale, scale, top, height).translate(x - top, y - height);
5850 R.format = function (token, params) {
5851 var args = R.is(params, array) ? [0][concat](params) : arguments;
5852 token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
5853 return args[++i] == null ? E : args[i];
5857 R.ninja = function () {
5858 oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
5863 [ property (object) ]
5865 * You can add your own method to elements. This is usefull when you want to hack default functionality or
5866 * want to wrap some common transformation or attributes in one method. In difference to canvas methods,
5867 * you can redefine element method at any time. Expending element methods wouldn’t affect set.
5869 | Raphael.el.red = function () {
5870 | this.attr({fill: "#f00"});
5873 | paper.circle(100, 100, 20).red();
5877 // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
5878 (function (doc, loaded, f) {
5879 if (doc.readyState == null && doc.addEventListener){
5880 doc.addEventListener(loaded, f = function () {
5881 doc.removeEventListener(loaded, f, false);
5882 doc.readyState = "complete";
5884 doc.readyState = "loading";
5886 function isLoaded() {
5887 (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : eve("DOMload");
5890 })(document, "DOMContentLoaded");
5892 oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
5895 * Eve 0.2.1 - JavaScript Events Library
5897 * Copyright (c) 2010 Dmitry Baranovskiy (http://dmitry.baranovskiy.com/)
5898 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
5901 var eve = R.eve = (function () {
5902 var version = "0.2.1",
5903 has = "hasOwnProperty",
5904 separator = /[\.\/]/,
5907 eve = function (name, scope) {
5909 args = Array.prototype.slice.call(arguments, 2),
5910 listeners = eve.listeners(name),
5912 for (var i = 0, ii = listeners.length; i < ii; i++) {
5914 listeners[i].apply(scope, args);
5916 errors.push({error: ex && ex.message || ex, func: listeners[i]});
5919 if (errors.length) {
5923 eve.listeners = function (name) {
5924 var names = name.split(separator),
5936 for (i = 0, ii = names.length; i < ii; i++) {
5938 for (j = 0, jj = es.length; j < jj; j++) {
5940 items = [e[names[i]], e[wildcard]];
5946 out = out.concat(item.f || []);
5954 eve.on = function (name, f) {
5955 var names = name.split(separator),
5957 for (var i = 0, ii = names.length; i < ii; i++) {
5959 !e[names[i]] && (e[names[i]] = {n: {}});
5963 for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) {
5968 eve.unbind = function (name, f) {
5969 var names = name.split(separator),
5974 for (var i = 0, ii = names.length; i < ii; i++) {
5975 for (var j = 0; j < cur.length; j += splice.length - 2) {
5978 if (names[i] != wildcard) {
5980 splice.push(e[names[i]]);
5983 for (key in e) if (e[has](key)) {
5984 splice.push(e[key]);
5987 cur.splice.apply(cur, splice);
5990 for (i = 0, ii = cur.length; i < ii; i++) {
5995 for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) {
5999 !e.f.length && delete e.f;
6001 for (key in e.n) if (e.n[has](key) && e.n[key].f) {
6002 var funcs = e.n[key].f;
6003 for (i = 0, ii = funcs.length; i < ii; i++) if (funcs[i] == f) {
6007 !funcs.length && delete e.n[key].f;
6011 for (key in e.n) if (e.n[has](key) && e.n[key].f) {
6020 eve.version = version;
6021 eve.toString = function () {
6022 return "You are running Eve " + version;
6029 eve.on("DOMload", function () {