Поддержка линейной области графика гистограммы гистограмм
Поддерживает несколько браузеров
Использовал SVG VML
Кода -копия выглядит следующим образом:
<! Doctype html public "-// w3c // dtd xhtml 1.0 transitional // en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<голова>
<meta http-equiv = "content-type" content = "text /html; charset = utf-8" />
<title> smiplechart </title>
<стиль типа = "text/css">
.cc {
Высота: 450px; Ширина: 800px; Граница: 1PX SOLID #999; позиция: относительно; Маржа: 20px;
}
</style>
</head>
<тело>
<div id = 't'> </div>
<div id = 't1'> </div>
<div id = 'line'> </div>
<div id = 'rea'> </div>
<div id = 'Zhu'> </div>
<div id = 'zhu1' style = "height: 600px;"> </div>
<div id = 'segmentx'> </div>
<div id = 'segmenty'> </div>
<div id = 'pie'> </div>
<div id = 'pies'> </div>
<div id = 'vv' style = 'height: 300px; Ширина: 520px; '> </div>
<script type = "text/javascript">
(function (doc, неопределенная) {
var win = это,
uuuid = -1,
hassvg = win.svgangle || Doc.Implementation.hasfeature ("http://www.w3.org/tr/svg11/feature#basicstructure", "1.1"),
isie = /msie/i.test(navigator.useragent) &&! win.opera,
path = hassvg? 'd': 'path',
seal = hassvg? 'z': 'e',
математика = математика,
mathround = math.round,
mathfloor = math.floor,
mathceil = math.ceil,
mathmax = math.max,
mathmin = math.min,
mathabs = math.abs,
mathcos = math.cos,
mathsin = math.sin,
M = 'm',
L = 'l';
Win. $$ = function (id) {
return document.getElementbyId (id);
};
win.extend = function () {
var target = аргументы [0] || {}, i = 1, length = arguments.length, deep = true, опции;
if (typeof target === "boolean") {
Deep = Target;
Target = аргументы [1] || {};
i = 2;
}
if (typeof target! == "Object" && object.prototype.tostring.call (target)! = "
target = {};
for (; i <length; i ++) {
if ((options = аргументы [i])! = null)
для (имя var в параметрах) {
var src = target [name], copy = options [name];
if (target === Copy)
продолжать;
if (deep && copy && typeof copy === "object" &&! copy.nodetype) {
target [name] = arguments.callee (deep, src || (copy.length! = null? []: {}), copy);
}
иначе if (копия! == не определен)
Target [name] = copy;
}
}
вернуть цель;
};
win.each = function (объект, обратный вызов, args) {
var name, i = 0, length = object.length;
if (args) {
args = array.prototype.slice.call (аргументы) .slice (2);
if (длина === не определен) {
для (имя в объекте)
if (callback.apply (object [name], [name, object [name]]. concat (args)) === false)
перерыв;
} еще
для (; i <длина; i ++)
if (callback.apply (object [i], [i, object [i]]. concat (args)) === false) //
перерыв;
} еще {
if (длина === не определен) {
для (имя в объекте)
if (callback.call (object [name], name, object [name]) === false)
перерыв;
} еще
for (var value = object [0];
i <length && callback.call (value, i, value)! == false; value = object [++ i]) {}
}
вернуть объект;
};
win.contains = function (p, c) {
if (! P ||! C) вернуть false;
if (p === c) вернуть true;
вернуть Isie
? P.Contains (c)
: p.comparedocumentposition (c) == 20
? истинный
: ЛОЖЬ;
};
// ---------------------------------------------------------------
Функция ProcessPoint (x) {
вернуть Изи? ~~ x.tofixed (0): ~~ x.tofixed (0) + 0,5;
};
Функция CalTextLen (TXT, CSSSTR) {
var span = doc.createElement ('span');
if (cssstr) {
typeof cssstr === 'String'
? span.style.csstext = cssstr
: extend (span.style, cssstr);
}еще{
Extend (span.style, {
fontsiz: '12px',
Fontfamily: «Lucida Grande», «Люсида без Unicode», Verdana, Arial, Helvetica, Sans-Serif '
});
}
span.innerhtml = txt || '';
span.style.visibility = 'hidden';
doc.body.appendchild (span);
var width = span.offsetwidth,
высота = span.offsetheight;
Doc.Body.RemoveChild (SPAN);
return {w: ширина, h: высота};
};
Угол функции (r, center, o, jingdu) {
var hudu = math.pi*2*(o/360),
x = center [0]+ r*math.sin (hudu),
y = center [1]+ -r*math.cos (hudu);
return [x.tofixed (jingdu || 0), y.tofixed (jingdu || 0)];
}
Функция xx (a, b, lenenum) {
var t = 1000,
STF = ((b*ta*t)/lenenum)/t,
arr = [1,2,2,5,5,10],
c = 1,
V;
// Кардинальность разделительной линии составляет [1, 2, 2,5, 5, 10] Этот шаг состоит в том, чтобы выяснить, какой диапазон принадлежит интервал к
if (stf <arr [0]) {
while (stf <arr [0]) {
c = C*10;
arr [0] = arr [0]/c;
}
Каждый ([1,2,2,5,5,10], функция (i, o) {
arr [i] = o/c;
});
} else if (stf> arr [4]) {
while (stf> arr [4]) {
c = C*10;
arr [4] = arr [4]*c;
}
Каждый ([1,2,2,5,5,10], функция (i, o) {
arr [i] = o*c;
});
}
// Следуйте интервалу, чтобы найти самый близкий в интервале
каждый (arr, function (i, o) {
if (stf <= o) {
v = o;
вернуть ложь;
}
});
var bj = (mathabs (a)*t)/(v*t),
ba = 0,
isz = bj! == parseint (bj);
ISZ
&& a> 0
? BA = -A%V*T.
: ba = (mathabs (a)%vv)*t;
a = (a*t+ba)/t;
b = (b*t+(b%v === 0? 0: (vb%v))*t)/t;
// Посмотрите, сколько линий осталось и не нарисовано
var num = math.max (0, linenum - math.round ((ba)/v));
if (a> = 0) {
// координатное сравнение целое число
if (a! = 0 && num! = 0 && a%10! == 0) {
while (a! = 0 && num! = 0) {
a = (a*tv*t)/t;
num-;
if ((a*tv*num*t)/10000> 0 && a%10 === 0)
перерыв;
}
}
if (num! = 0) {
while (num! == 0) {
b = (b*t+v*t)/t
num-;
}
}
}еще{
// координатное сравнение целое число
if (b <0 && num! = 0) {
while (b! = 0 && num! = 0 && b%10! == 0) {
b = (b*t+v*t)/t;
num-;
if ((b*t+v*num*t)/t <0 && b%10 === 0)
перерыв;
}
}
if (num! = 0) {
while (num! == 0) {
a = (a*tv*t)/t
num-;
}
}
}
return {min: a, max: b, stf: v};
}
// -------------------------------------------------------------------------------------------------------
// Создать некоторые творения элементов SVG VML и удалить стили атрибутов == Некоторые операции
win.vector = function () {};
Vector.Prototype = {
$ c: function (graphic, nodeName) {
this.Element = this [0] = doc.createElementns ('http://www.w3.org/2000/svg', рядное название);
this.graphic = graphic;
вернуть это;
},
attr: function (hash, val) {
var elem = this.element,
ключ,
ценить;
if (typeof hash === 'string') {
if (val === не определено) {
return elem.getattribute (hash);
}еще{
elem.setattribute (hash, val);
вернуть это;
}
} еще {
для (ключ в хэш) {
value = hash [ключ];
if (key === path) {
value && value.join
&& (value = value.join (''));
/(NAN | |^$)/. Тест (значение)
&& (value = 'm 0 0');
}
elem.setattribute (ключ, значение)
}
}
вернуть это;
},
css: function (hash) {
для (var key in hash) {
isie && key == "непрозрачность"
? это [0] .style ['filter'] = "alpha (opacity ="+ hash [key] * 100+ ")"
: this [0] .style [key] = hash [key];
}
вернуть это;
},
on: function (EventName, Handler) {
var self = это;
/* это.
handler.call (self)
},ЛОЖЬ);*/
this.element ['on' + eventName] = function (e) {
E = E || Win.Event;
handler.call (self, e);
}
вернуть это;
},
appendTo: function (parent) {
if (parent) {
Parent.Element
? parent.element.appendchild (this.element)
: parent.appendchild (this.element)
} еще {
this.graphic.container.appendchild (this.element);
}
вернуть это;
},
AddText: function (str) {
var elem = this.element;
if (elem.nodename === 'text') {
elem.appendchild (doc.createtextnode (str+''));
}
вернуть это;
},
setOpacity: function (v) {
this.attr ('fill-opbity', v);
вернуть это;
},
setSize: function (v) {
это [0] .nodeName === 'Circle'
? this.attr ('r', 4+(v === 0? 0: 2))
: this.attr ({'weadth': v});
вернуть это;
},
tofront: function () {
это [0] .parentnode.appendchild (это [0]);
вернуть это;
},
show: function () {
это [0] .style.display = 'block';
вернуть это;
},
скрыть: function () {
это [0] .style.display = 'none';
вернуть это;
},
Уничтожить: function () {
// уничтожить узлы ............
var node = this [0] || этот;
node.onmouseover = node.onmouseout = node.onclick = null;
node.parentnode
&& node.parentnode.removechild (node);
вернуть это;
}
};
// -------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------
// Если это VML для изменения некоторых из этих методов
if (! hassvg) {
// -------------------------------------------------------------------------------------------------------------------------
doc.createstyleSheet (). AddRule (". VML", "Поведение: URL (#по умолчанию#VML); DISPLAY: INLINE BLOCK; Положение: Абсолют; слева: 0PX; TOP: 0PX");
! doc.namespaces.vml &&!+"/v1";
doc.namespaces.add ("vml", "urn: схемы-microsoft-com: vml");
// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
extend (ecector.prototype, {
$ c: function (graphic, nodeName) {
var name = NodeName || 'форма';
this.element = this [0] = (name === 'div' || name === 'span')
? doc.createElement (имя)
: doc.createElement ('<vml:'+name+'>');
this.graphic = graphic;
вернуть это;
},
/*on: function (EventName, Handler) {
var self = это;
this.element.attachevent ("on" + eventname, function () {
handler.call (self);
});
вернуть это;
},*/
AddText: function (txt) {
это [0] .innerhtml = txt || '';
вернуть это;
},
setSize: function (v) {
это [0] .StrokeWeight = V;
вернуть это;
},
setOpacity: function (v) {
this.opacity.opacity = v;
вернуть это;
}
});
}
// -----------------------------------------------------------------------------------------------
// категория рисования
// ------------------------------------------------------------
win.smiplechart = function () {
this.init.apply (это, аргументы);
};
smilechart.list = [];
smilechart.timer = null;
smilechart.lazyload = function (id) {
id = id || 0 ''
smilechart.list [id]
&& smiplechart.list [id] .loadme ();
};
smilechart.prototype = {
параметры: {
Диаграммы: {
Paddingright: 20,
радиус: 200,
Стиль: {
Fontfamily: «Lucida Grande», «Люсида без Unicode», Verdana, Arial, Helvetica, Sans-Serif ',
Fontsize: '12px',
Фон: '#ffffff'
}
},
заголовок: {
Текст: '',
y: 10,
Стиль: {
Fontfamily: 'Verdana, Arial, Helvetica, Sans-Serif',
Fontsize: '16px',
шрифт: 'смелый'
}
},
субтитры: {
Текст: '',
Y: 30,
Стиль: {
Fontfamily: 'Verdana, Arial, Helvetica, Sans-Serif',
Fontsize: '12px',
Цвет: '#111'
}
},
Юнит: {
Текст: '',
Стиль: {
Fontfamily: 'Verdana, Arial, Helvetica, Sans-Serif',
Fontsize: '12px',
Цвет: '#111'
},
ЛЕНЕНЕМ: 10
}
},
init: функция (контейнер, параметры) {
ClearTimeout (smipleChart.timer)
var self = это;
this.width = container.offsetwidth;
this.height = container.offsetheight;
this.currlist = {};
this.uuuid = ++ uuuid;
this.timer = null;
// Основная форма сбора группы рисования
// {id: {dom: xx, show: true}}
this.maingroup = {};
// Что следует использовать при сегментировании, чтобы знать, какие из них скрыты, потому что это включает перераспределение
this.hidelist = {};
// рисунок в SVG должен иметь SVG Tag VML и использовать Div
this.container = hassvg
? Новый Vector (). $ C (1, 'svg')
.attr ({
xmlns: 'http://www.w3.org/2000/svg',
Версия: '1.1',
Ширина: это.
Высота: это
})
.css ({fontsize: '12px'})
.appendto (контейнер)
: new Vector (). $ C (1, 'div')
.css ({
Fontsize: '12px',
ширина: this.width +'px',
Высота: это. Хист+'px'
})
.appendto (контейнер);
this.Loading = container.AppendChild (doc.createElement ('img'));
this.loading.setattribute ('src', 'http: //images.cnblogs.com/cnblogs_com/wtcsy/192373/r_loading.gif');
this.loading.style.position = 'Absolute';
this.Loading.Style.top = container.Offsetheight/2- this.Loading.OffSetheight/2+'px';
this.loading.style.left = intainer.offsetwidth/2- this.loading.offsetwidth/2+'px';
var c = extend (true, {}, this.options),
opts = this.opts = extend (true, c, options),
style = extend (opts.charts.style, {
Ширина: это.
Высота: это
});
smileChart.list [this.Uuuid] = this;
smilechart.timer = settimeout (function () {
smilechart.lazyload ();
}, 200);
},
LoadMe: function () {
var opts = this.opts,
self = это,
type = opts.charts.type;
this.container = this.container
.on ('mouseout', function (e) {
var elem = e.relatedtarget || E.ToElement;
if (! Содержит (это [0], elem)) {
self.hidetooltip ();
self.currlist.dot
&& self.currlist.dot.setsize (0);
self.currlist.line
&& self.currlist.line.setsize (1.5);
self.currlist = {};
}
})
.css ({display: 'none'}) [0];
// Некоторые параметры, необходимые при расчете пластины для рисования
this.getdrawarea ()
. CreateTooltip () // Создать поле для информации
.drawtitle () // Нарисуйте заголовок
// Нарисуйте тарелку
'Line, область, Pie'.indexof (type)> = 0
&& (opts.charts.panel = 'x');
'Pie, pies'.indexof (type) <0
&& this.drawpanel ();
this.DrawleGend (Opts.Legend.Type); // рисовать цветовые блок
var type = {
Линия: 'Drawline',
область: 'drawarea',
столбцы: 'DrawColumns',
Пирог: 'Drawpie',
Пироги: «Нариты»,
Сегмент: 'Drawsegment'
} [opts.charts.type];
// начать рисунок .........
это [type] ();
// Удалить узел
this.loading.parentnode.removechild (this.loading);
// Отключить ссылку
this.Loading = null;
this.container.style.display = '';
settimeout (function () {
smilechart.lazyload ((++ self.uuuid)+'');
}, 10)
},
CreateElement: function (NodeName) {
вернуть новый Vector (). $ C (это, nodeName);
},
Группа: функция (имя) {
вернуть это. CreateElement (hassvg? 'g': 'div'). attr ('mark', name);
},
getdrawarea: function () {
var opts = this.opts,
ширина = this.width,
высота = это.
title = opts.title,
subtitle = opts.subtitle,
область = {
// Удалить ширину текста шкалы на левой стороне оси координаты (оцененная) 80 является фиксированным значением, и только 80 остается в левой стороне фиксированного значения.
Района, ширина: ширина - 80,
// Удалить высоту текста и маркировки под осью
Район Хейт: высота - 40,
// Положение X происхождения будет рассчитано ниже
Startx: 0,
// Положение Y происхождение будет рассчитано ниже
Starty: 0,
// При рисовании круговой диаграммы с x координата центра необходимо знать положение центра круга.
CENTERX: 0,
// При рисовании круговой диаграммы с координатой Y в центре вам нужно знать положение центра круга.
Центр: 0
};
// Если основной заголовок существует, вычтите высоту основного заголовка, в противном случае вычитайте высоту 10
Area.areaheight -= (title.text! == '')
? Title.y
: 10;
// Удалить высоту подзаголка
Area.areaheight -= (subtitle.text! == '')
? subtitle.y
: 10
Area.Startx = 80;
область. Starty = высота - 40;
// положение центра круга
область.centerx = ширина / 2;
область. Центральная сторона = высота / 2;
// Оставьте немного места справа
Area.AreaWidth -= 20;
// Оставьте немного интерната на вершине
Area.areaheight -= 15;
Opts.Area = область;
вернуть это;
},
DraitTitle: function () {
var opts = this.opts,
self = это,
arr = [opts.title, opts.subtitle, opts.yunit],
// Основные параметры позиции 3 координат заголовка
config = [
{
X: This.width / 2,
Y: Opts.title.Y
},
{
X: This.width / 2,
Y: Opts.subtitle.Y
},
{
X: Opts.yunit.x,
y: this.height / 2 - 20
}
],
tpanel = this.group ('title')
.appendto ();
каждый (arr, function (i, title) {
var text = title.text;
if (text) {
var elem = self.basedraw.span (self, {
«Текст-анго»: 'Least',
X: Mathmax (config [i] .x - caltextlen (text, title.style) .w/2,10),
y: config [i] .y
}, CalTextLen (title.Text, title.style) .h)
.css (title.style)
.AdDtext (текст)
.appendto (tpanel);
// Если это 2, это означает, что субтитры используется, чтобы поместить его вертикально
if (i === 2) {
Хассвг
? elem.attr ({transform: 'utate (270,'+(opts.yunit.x+10)+','+self.height / 2+')'})
: (elem.element.style.filter = 'progid: dximagetransform.microsoft.basicimage (rowation = 3)')
}
}
});
вернуть это;
},
// рисование тарелок более хлопотно
DrawPanel: function (type) {
varopts = this.opts,
self = это,
область = opts.area,
chartstype = opts.charts.type,
issegment = chartstype === 'segment',
// - тип горизонтальной или вертикальной пластины
type = opts.charts.panel || 'x';
// нижняя пластина
var drawareawidth = area.areawidth,
DrawareaHeight = aean.areaheight,
// координаты происхождения
startx = area.startx,
starty = gene.starty;
var alldata = [],
minvalue = 0,
maxvalue = 10,
// количество строк может быть только от 1 до 10
LENENUM = Mathmin (10, Mathmax (Opts.yunit.linenum, 1)),
персонал;
// Объединение всех данных
каждый (opts.chartdata, function (i, o) {
// Если это гистограмма, она суммируется для всех данных
иссегмент
? каждый (o.data, function (j, d) {
Alldata [J]
? alldata [j] = alldata [j] + (~~ d)
: alldata [j] = ~~ d;
})
: alldata = alldata.concat (o.data)
});
// Сортировать все данные, чтобы найти максимальное значение и минимальное значение ниже
alldata.sort (function (a, b) {return ab});
// Завершить максимальное значение и минимальное значение
maxvalue = alldata [alldata.length - 1];
каждый (alldata, function (i, o) {
if (o! == null) {
minvalue = o;
вернуть ложь;
}
});
// контейнер с основной пластиной
var panel = this.group ('panel'). AppendTo ();
var result = xx (minvalue, maxvalue, lenenum),
min = result.min,
max = result.max,
f = result.stf;
иссегмент
&& (min = 0);
// означает, что горизонтальная координата или двойная координата нарисованы
if (type.tolowercase () === 'x') {
// подземный интервал
varxpices = drawareawidth / opts.xunit.units.length,
// центральная точка единичного интервала
offset = xpices / 2,
ypices = drawareaHeight / lenenum;
// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var y = hassvg? 5: 10,
t = 1000,
охватывать;
каждый (opts.xunit.units, function (i, d) {
self.basedraw.path (self, {
граница: 1,
Bordercolor: '#C0C0C0',
isfill: ложь,
путь : [
М,
ProcessPoint (startX + (i * xpices)),
ProcessPoint (Starty),
L,
ProcessPoint (startX + (i*xpices)),
ProcessPoint (Starty + 5)
]
}).
appendto (панель);
span = self.basedraw.span (self, {
x: startx + offset + (i * xpices),
Y: Starty+y,
«Текст-анго»: «Средний»
})
.css ({
Fontfamily: 'Verdana, Arial, Helvetica, Sans-Serif',
Fontsize: '12px'
})
.addtext (opts.xunit.units [i])
.appendto (панель) [0];
! Hassvg
&& (span.style.left = parseint (span.style.left) - span.offsetwidth/2+'px');
});
// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
for (i = 0; i <= linenum; i ++) {
self.basedraw.path (self, {
граница: 1,
Bordercolor: '#C0C0C0',
isfill: ложь,
Путь: [m, startx, processpoint (starty - (i * ypices)), l, processpoint (startx + drawareawidth), processpoint (starty - (i * ypices))]]]]
})
.css ({zindex: -10})
.appendto (панель);
var span = self.basedraw.span (self, {
X: Startx - 15,
y: starty - i * ypices -caltextlen (min+i * f+''). H/2,
«Текст-анго»: «Средний»
})
.css ({
'font-family': 'verdana, arial, helvetica, sans-serif',
'font-size': '12px',
Ширина: «40px»,
дисплей: 'block',
Textalign: 'right'
})
.AdDtext ((min*t+(i*t*f/t)*t)/t+'')
.appendto (панель) [0];
if (! hassvg) {
span.style.top = parseint (span.style.top) + span.offsetheight/2 -5 + 'px';
span.style.left = parseint (span.style.left) -35+'px'
}
}
}еще{
// подземный интервал
varypices = drawareaheight / (opts.xunit.units.length),
// центральная точка единичного интервала
offset = math.round (ypices / 2),
x = hassvg? 25: 70,
y = hassvg? 0: 5,
охватывать
каждый (opts.xunit.units, function (i, d) {
self.basedraw.path (self, {
граница: 1,
Bordercolor: '#C0C0C0',
isfill: ложь,
путь : [
М,
ProcessPoint (startX-5),
ProcessPoint (starty-i * ypices),
L,
ProcessPoint (startX),
ProcessPoint (starty-i * ypices),
]
})
.appendto (панель);
span = self.basedraw.span (self, {
X: Startx - x,
y: starty -i * ypices-offset-caltextlen (d) .h/2 + y,
«Текст-анго»: «Средний»
})
.css ({
Fontfamily: 'Verdana, Arial, Helvetica, Sans-Serif',
Fontsize: '12px',
Ширина: '60px',
Textalign: 'right'
})
.AdDtext (D)
.appendto (панель)
});
var xpices = drawareawidth / lenenum;
for (var i = 0; i <= linenum; i ++) {
self.basedraw.path (self, {
граница: 1,
Bordercolor: '#C0C0C0',
isfill: ложь,
путь : [
М,
ProcessPoint (startX + (i * xpices)),
ProcessPoint (Starty),
L,
ProcessPoint (startX + (i*xpices)),
ProcessPoint (Starty - DrawareaHeight)
]
}).
appendto (панель);
self.basedraw.span (self, {
X: startx - caltextlen (min+i * f+''). w/2+i * xpices,
Y: Starty,
'Текст-ангор': 'ушел'
})
.css ({
Fontfamily: 'Verdana, Arial, Helvetica, Sans-Serif',
Fontsize: '12px'
})
.AdDtext (min+i*f+'')
.appendto (панель);
}
}
// -------------------------------------------------------------------------------------------------
// Поскольку отправная точка, вероятно, не запускается с 0, поэтому значение части 0 должно быть добавлено в начальной точке.
var jianju = 0;
if (min> 0) jianju = min;
if (max <0) jianju = max;
startx = opts.charts.panel === 'x'? startX: startx-xpices*(min/f);
starty = opts.charts.panel === 'x'? starty + ypices*(min/f): starty;
opts.draw = {
startx: startx, // x отправная точка оси
Starty: Starty, // y Oxis отправная точка
Xpices: xpices, // ширина каждой части оси x
Ypices: Ypices, // ширина каждой части оси Y
смещение: смещение, // x Офсетное положение центральной точки точки с отдельной ветвью
jianjuy: jianju*ypices/f,
jianjux: jianju*xpices/f,
корм: f // сколько там оси Y
}
вернуть это;
},
CreateTooltip: function () {
// группа
this.tipc = this.group ('tip')
.css ({zindex: 200, высота: '20px', ширина: '20px', позиция: 'Absolute'})
.appendto ()
.скрывать()
// нарисовать кадр на основе
this.tipbox = this.basedraw.rect (this, {arc: 0.22, fill: '#ffff', border: 2, bordercolor: '#606060'})
.appendto (this.tipc)
// Поскольку G в SVG может быть непосредственно расположена, но группа, рендеринг в VML, очень медленная, поэтому DIV изменяется, поэтому родитель здесь не совпадает с иностранным
var p = isie? this.tipbox: this.tipc;
this.tiptxtcontainer = this.basedraw.text (this, {fill: '#000000', x: 5, y: 19, 'text-anchor': 'Left'})
.css ({
Fontfamily: 'Verdana, Arial, Helvetica, Sans-Serif',
Fontsize: '12px',
фон: '#fff'
})
.appendto (p);
this.tiptext = doc.createTextNode ('');
this.tiptxtcontainer [0] .appendchild (this.tiptext);
вернуть это;
},
ShowTooltip: функция (obj, x, y, data) {
/*var txt = obj.name + ':' + data,
size = caltextlen (txt, this.tiptxtcontainer [0] .style.csstext),
pos = {x: x - (size.w + 5 * 2)/2, y: y - 32};
this.tipc
.tofront ()
.показывать();
if (hassvg) {
this.tipc.attr ({transform: 'translate ('+pos.x+','+pos.y+')'});
this.tipbox
.attr ({width: size.w + 5 * 2, высота: размер.
}еще{
this.tipc.css ({left: pos.x, top: pos.y});
this.tipbox
.css ({width: size.w + 5 * 2, высота: size.h + 5 * 2})
this.tipbox [0] .strokecolor = obj.color || '#000';
}
this.tiptext.nodevalue = txt || '';*/
ClearTimeOut (this.Timer);
var txt = obj.name + ':' + data,
self = это,
size = caltextlen (txt, this.tiptxtcontainer [0] .style.csstext),
pos = {x: x - (size.w + 5 * 2)/2, y: y - 32};
if (hassvg) {
Self.tipbox
.attr ({width: size.w + 5 * 2, высота: размер.
}еще{
Self.tipbox
.css ({width: size.w + 5 * 2, высота: size.h + 5 * 2})
self.tipbox [0] .strokecolor = obj.color || '#000';
}
this.tiptext.nodevalue = txt || '';
if (this.tipc [0] .style.display === 'none') {
Хассвг
? self.tipc.attr ({transform: 'translate ('+pos.x+','+pos.y+')', pos: pos.x+'-'+pos.y})
: self.tipc.attr ({pos: pos.x+'-'+pos.y}). css ({left: pos.x, top: pos.y});
this.tipc
.tofront ()
.показывать();
}еще{
var move = function (t, b, c, d) {
вернуть C*(t/= d)*t + b;
},
t = 0,
b = self.tipc.attr ('pos'). split ('-'),
c = [pos.x, pos.y],
d = 5;
this.timer = setInterval (function () {
if (t <d) {
t ++;
var x = move (t, ~~ b [0], (~~ c [0])-(~~ b [0]), d),
y = move (t, ~~ b [1], (~~ c [1])-(~~ b [1]), d);
Хассвг
? self.tipc.attr ({transform: 'translate ('+x+','+y+')', pos: x+'-'+y})
: self.tipc.attr ({pos: x+'-'+y}). css ({слева: x, top: y});
}еще{
ClearTimeOut (Self.Timer);
}
}, 1);
};
},
hidetooltip: function () {
this.tipc.hide ();
},
Drawlegend: function (type, redraw) {
var self = это,
opts = this.opts,
isline = opts.charts.type === 'line',
// размер цветового блока
t_width = 20,
t_height = 20,
// расстояние между блоками
t_space = 5,
datas = opts.chartdata,
len = datas.length,
css = opts.legend.style,
// Если максимальная длина является продольной, максимальная длина требуется
maxwidth = 10,
maxheight = 30,
// местоположение этой вещи
ouring_pos = opts.legend.pos? opts.legend.pos: [2,2],
// Показать скрытые группы функций
handle = function (i) {
var g = self.maingroup ['chart'+i],
issegment = opts.charts.type === 'segment';
if (g.show) {
g.chart.hide ();
g.show = false;
Хассвг
? this.attr ({fill: '#ccc'})
: this [0] .style.color = '#ccc';
// Если это сегментированная картина, она будет включать перераспределение.
if (issegment) {
self.hidelist [i] = '';
var maingroup = self.maingroup;
для (var name в maingroup) {
var parent = maingroup [name] .chart,
узлы = родитель [0] .ChildNodes,
len = nodes.length;
// уничтожить вещи, нарисованные на картинке
for (var i = len-1; i> = 0; i-) {
Vector.prototype.destroy.call (узлы [i])
}
}
// перекрасить
self.drawsegment ();
}
}еще{
g.chart.show ();
g.show = true;
Хассвг
? this.attr ({fill: '#000'})
: this [0] .style.color = '#000'
if (issegment) {
Удалить Self.hidelist [i];
var maingroup = self.maingroup;
для (var name в maingroup) {
var parent = maingroup [name] .chart,
узлы = родитель [0] .ChildNodes,
len = nodes.length;
for (var i = len-1; i> = 0; i-) {
Vector.prototype.destroy.call (узлы [i])
}
}
self.drawsegment ();
}
}
},
arr = [];
type = type || 'lotheral';
var LegendPanel = self.Group ('Legend')
.appendto ();
if (type === 'lotheral') {
// Если это горизонтально
var top = orig_pos [1] + 5,
th = hassvg? 0: 3,
слева = orig_pos [0] + 5;
каждый (DataS, function (i, d) {
слева = i === 0? Слева: t_space+слева;
// Рассчитайте местоположение всех левых
// Если это линейная диаграмма, нарисуйте чертеж в виде линейной диаграммы
if (isline) {
self.basedraw.path (self, {
граница: 1,5,
Bordercolor: D.color,
isfill: ложь,
путь : [
М,
Left.tofixed (0),
(вверху+10) .tofixed (0),
L,
(слева+25) .tofixed (0),
(вверху+10) .tofixed (0)
]
})
.appendto (LegendPanel);
self.basedraw [d.dottype || 'circle'] (self, {
X: слева+12,
y: топ+10,
R: 4,
FillColor: D.Color
})
.appendto (LegendPanel);
}еще{
self.basedraw.rect (self, {
дуга: 0,1,
заполнить: d.color,
граница: 1,
Bordercolor: D.color,
слева: слева,
Верх: Верх,
ширина: t_width+'px',
Высота: T_height+'px'
})
.appendto (LegendPanel)
}
слева = слева + t_width + 2 + t_space;
var w = caltextlen (d.name, css) .w
self.basedraw.span (self, {
«Текст-анго»: 'Least',
X: слева,
Y: Top+Th
})
.css (extend (css, {coursor: 'pointer'}))
.on ('click', function () {
handle.call (это, i);
})
.AdDtext (D.Name)
.appendto (LegendPanel);
слева = слева + w;
});
this.basedraw.rect (это, {
дуга: 0,1,
заполнить: «нет»,
граница: 1,5,
Bordercolor: '#6666666',
Ширина: слева+ t_space- orig_pos [0],
Высота: Максхайт,
Слева: Orig_pos [0],
Верх: Orig_pos [1]
})
.appendto (LegendPanel);
}еще{
var top = orig_pos [1] + 5,
th = hassvg? 0: 3,
слева = orig_pos [0] + 5;
каждый (DataS, function (i, d) {
top = i === 0? Верх: T_SPACE + TOP;
self.basedraw.rect (self, {
дуга: 0,1,
заполнить: d.color,
граница: 1,
Bordercolor: D.color,
слева: слева,
Верх: Верх,
ширина: t_width+'px',
Высота: T_height+'px'
})
.appendto (LegendPanel);
var h = caltextlen (d.name, css) .h;
self.basedraw.span (self, {
«Текст-анго»: 'Least',
X: слева+t_width+2+t_space,
Y: Top+Th
})
.css (extend (css, {coursor: 'pointer'}))
.AdDtext (D.Name)
.on ('click', function () {
// Если это многослойная круговая диаграмма, она не может быть скрыта
if (opts.charts.type === 'pies') return;
handle.call (это, i);
})
.appendto (LegendPanel);
top = top + h + t_space;
maxwidth = math.max (maxwidth, caltextlen (d.name, css) .w);
});
this.basedraw.rect (это, {
дуга: 0,1,
заполнить: «нет»,
граница: 1,5,
Bordercolor: '#6666666',
Ширина: максимальная мощность+22+15,
Высота: вверху+t_space-orig_pos [1],
Слева: Orig_pos [0],
Верх: Orig_pos [1]
})
.appendto (LegendPanel);
}
вернуть это;
},
Drawline: function () {
var self = это,
opts = this.opts,
Draw = Opts.Draw;
каждый (opts.chartdata, function (i, o) {
var id = 'диаграмма'+i,
LineGroup = self.Group (id)
.appendto ();
self.maingroup [id] = {
Диаграмма: LineGroup,
Показать: правда
};
var path = [m],
data = o.data,
линия;
для (var i = 0, l = data.length; i <l; i ++) {
if (data [i] == null) {
// Если эти данные не существуют и не являются первым путем данных, добавьте M к ним
if (path [path.length - 1]! == m)
path.push (m);
}еще{
// Если это не первый путь данных, добавьте L
i! == 0 && path.push ("l");
// Если первый нулевой, а не первый, кто удалил L
if (i> 0 && data [i - 1] == null)
path.pop ();
// Рассчитать положение x и y точки
var x = draw.startx + draw.offset + (i * draw.xpices),
y = draw.starty - data [i] * (draw.ypices / draw.feed);
if (isie) {
x = parseint (x);
y = parseint (y);
}
path.push (x);
path.push (y);
// рисовать точки
var dottype = o.dottype || 'circle';
self.basedraw [dottype] (self, {
x: x,
Y: Y,
R: 4,
FillColor: O.Color
})
.attr ({data: data [i], pos: x+'-'+(y-5)})
.css ({zindex: 10, cursor: 'pointer'})
.on ('mouseover', (function (o, x, y) {
return function () {
if (self.currlist.dot) {
if (self.currlist.dot [0] === Это [0])
возвращаться;
self.currlist.dot.setize (0);
self.currlist.line.setsize (1.5);
}
это. setize (2);
line.setsize (2.5);
var pos = this.attr ('pos'). split ('-');
self.showtooltip (o, pos [0], pos [1], this.attr ('data'));
self.currlist.dot = this;
self.currlist.line = line;
}
}) (o, x, y))
/*. on ('mouseout', function () {
это. setize (0);
line.setsize (1.5);
})*/
.on ('click', function () {linegroup.tofront ();})
.appendto (LineGroup);
}
};
// рисовать сложенные линии
line = self.basedraw.path (self, {
граница: 1,5,
Bordercolor: O.Color,
isfill: ложь,
Путь: Путь
})
.css ({zindex: 5})
/*. on ('mouseover', function () {
это. setize (2.5);
})
.on ('mouseout', function () {
это. setize (1.5);
})*/
.on ('click', function () {linegroup.tofront ();})
.appendto (LineGroup);
});
вернуть это;
},
Drawarea: function () {
var self = это,
opts = this.opts,
Draw = Opts.Draw;
каждый (opts.chartdata, function (i, o) {
var id = 'диаграмма' + i,
reairgroup = self.group (id) .appendto ();
self.maingroup [id] = {chart: reairgroup, show: true};
// есть 2 пути, один - путь области, а другой - путь линии
var aea paintypath = [m, (draw.startx + draw.offset) .tofixed (0), (draw.starty-draw.jianjuy) .tofixed (0)],
path = [m],
data = o.data,
линия;
для (var n = 0, l = data.length; n <l; n ++) {
// Если данные пусты
var len = aeappath.length;
if (data [n] === null) {
// Если предыдущий не M, то нарисуйте снова, так что добавьте m
if (path [path.length - 1]! == m)
path.push (m);
// Если первый или фронт являются нулевыми, измените начальную точку координаты
Лен === 3
&& (gainpath [1] = (draw.startx +(n +1)*draw.xpices +draw.offset) .tofixed (0));
// Если предыдущий не является графиком области идентификатора конечного идентификатора, если первые данные являются нулевыми, следующая операция не будет выполнена
if (geapath [len - 1]! == seal && n! == 0) {
AreaPath = aeampath.concat ([[[[[[[[[[[[[[[[[[[[[[[
Площадь [Лен - 2],
(draw.starty-draw.jianjuy) .tofixed (0),
тюлень
]);
}
}еще{
n! == 0 && path.push (l);
AreaPath.push (L);
// Если предыдущие данные являются нулевыми, удалите предыдущий L
if (n> 0 && data [n - 1] == null) {
path.pop ();
// Если первый нулевой, не удаляйте L
n! == 1 && areapath.pop ();
}
var x = draw.startx + draw.offset + (n * draw.xpices),
y = draw.starty - data [n] * (draw.ypices / draw.feed);
if (isie) {
x = parseint (x);
y = parseint (y);
}
path.push (x);
path.push (y);
if (gain -path [len - 1] === seal) {
AreaPath = aeampath.concat ([[[[[[[[[[[[[[[[[[[[[[[
М,
x,
Parseint (draw.starty-draw.jianjuy),
L,
x,
у
]);
}еще{
AreaPath.push (x);
AreaPath.push (y);
}
// Если это последнее пункт
if (n === l - 1) {
AreaPath.push (x);
AreaPath.push (Parseint (Draw.starty-Draw.jianjuy));
}
// рисовать точки
self.basedraw [o.dottype || 'circle'] (self, {
x: x,
Y: Y,
R: 4,
FillColor: O.Color
})
.attr ({data: data [n], pos: x+'-'+(y-5)})
.on ('mouseover', (function (o, x, y) {
return function () {
if (self.currlist.dot) {
if (self.currlist.dot [0] === Это [0])
возвращаться;
self.currlist.dot.setize (0);
self.currlist.line.setsize (1.5);
}
это. setize (2);
line.setsize (2.5);
var pos = this.attr ('pos'). split ('-');
self.showtooltip (o, pos [0], pos [1], this.attr ('data'));
self.currlist.dot = this;
self.currlist.line = line;
}
}) (o, x, y))
/*. on ('mouseout', function () {
это. setize (0);
line.setsize (1.5);
// self.hidetooltip ()
})*/
.on ('click', function () {areaGroup.tofront ();})
.css ({zindex: 10, cursor: 'pointer'})
.appendto (reairgroup);
}
}
AreaPath.push (Seal)
self.basedraw.path (self, {
граница: 0,
isfill: правда,
FillColor: O.Color,
непрозрачность: 0,5,
Путь: Площадь
})
.css ({zindex: 5})
.appendto (reairgroup);
line = self.basedraw.path (self, {
граница: 1,5,
Bordercolor: O.Color,
isfill: ложь,
Путь: Путь
})
/*. on ('mouseover', function () {
Хассвг
? this.attr ({'weadth': 2,5})
: (это [0].
})
.on ('mouseout', function () {
Хассвг
? this.attr ({'weadth struck': 1,5})
: (это [0].
})*/
.on ('click', function () {areaGroup.tofront ();})
.css ({zindex: -1})
.appendto (reairgroup);
});
вернуть это;
},
DrawColumns: function () {
var self = это,
opts = this.opts,
Draw = Opts.Draw,
chartdata = opts.chartdata,
dataLen = chartdata.length,
// расстояние между несколькими столбцами
Columnspace = 3,
// сумма всех интервалов в позиции
ColumnPadding = ColumnSpace * DataLen + ColumnSpace,
// ширина каждого столбца
columnsize = self.opts.charts.panel === 'x'
? Number (((drail.xpices - columnpadding) / dataLen) .tofixed (0))
: Number ((((draw.ypices - columnpadding) / datalen) .tofixed (0));
каждый (chartdata, function (i, o) {
VAR DATA = O.Data,
id = 'диаграмма' + i,
isx = opts.charts.panel === 'x',
colgroup = self.group (id) .appendto (),
// начальная позиция каждой точки
start = self.opts.charts.panel === 'x'
? Draw.Startx + Columnspace + i*(ColumnSize + ColumnSpace)
: draw.starty + columnspace + i*(columnsize + columnspace)
self.maingroup [id] = {диаграмма: colgroup, show: true};
для (var j = 0, l = data.length; j <l; j ++) {
if (data [j] === null) продолжить;
// Если это боковая тарелка
if (isx) {
var x = number ((start + j *drail.xpices) .tofixed (0)),
y = number ((draw.starty-draw.jianjuy) .tofixed (0)),
Высота = number ((data [j] * (drail.ypices / draw.feed) -draw.jianjuy) .tofixed (0)),
Путь = [
М,
x,
y,
L,
x,
y -Hheight,
L,
x + columnsize,
y - высота,
L,
x + columnsize,
y,
тюлень
];
var pos = [x+columnSize/2,data[j]>0?y-height:draw.startY-draw.jianjuY];
}еще{
var x = Number((draw.startX+draw.jianjuX).toFixed(0)),
width = Number((data[j]*((draw.xPices / draw.feed))-draw.jianjuX).toFixed(0)),
y = Number((start - (j+1) *draw.yPices ).toFixed(0)),
path = [
M,
x,
y,
L,
x+ width,
y ,
L,
x + width,
y + columnSize,
L,
x ,
y+ columnSize,
тюлень
];
var pos = [draw.startX+draw.jianjuX+width/2,y];
}
self.baseDraw.path(self,{
border : 0,
isfill : true,
fillColor : o.color,
opacity : 1,
path : path
})
.attr({data:data[j],pos:pos[0]+'-'+pos[1]})
.css({zIndex:5,cursor:'pointer'})
.on('mouseover',(function(d){
return function () {
this.setOpacity(0.85);
var pos= this.attr('pos').split('-')
self.showTooltip(o,pos[0],pos[1],this.attr('data'));
}
})(data[j])
)
.on('mouseout',function(){
this.setOpacity(1);
})
.appendTo(colGroup);
}
});
return this;
},
drawPie : function(){
var self = this,
opts = this.opts,
area = opts.area,
rx = area.centerX,
ry = area.centerY,
inc = 0,
total = 0,
data = [],
cumulative = -0.25, // start at top;
circ = 2 * Math.PI,
radiu = mathMin(opts.charts.radius,mathMin(area.areaWidth/2,area.areaHeight/2)),
fraction,
half_fraction;
each(opts.chartData,function(i,o){
typeof o.data ==='object'
? (data.push((function(o){
var all =0;
for(var i in o)
all+=~~o[i]
return all
})(o.data)))
:data.push(mathAbs(o.data))
});
each(data,function(i,o){
total = total + o;
});
each(data,function(i,o){
var pieGroup = self.group('chart'+i).appendTo(),
s = inc/total*360,
e = (inc + o)/total*360,
name = opts.chartData[i].name,
size = calTextLen(name),
dot = angle(radiu,[rx,ry],s+(es)/2,2),
x = rx + (dot[0]-rx)/2 - size.w/2,
y = ry + (dot[1]-ry)/2 - size.h/2,
len = Math.sqrt((x-rx)*(x-rx)+(y-ry)*(y-ry)),
moveDisplacement = ((x-rx)*8/len)+','+((y-ry)*8/len);
inc = inc + o;
var value = Number(o);
fraction = total ? value / total : 0;
half_fraction = total ? (value / 2) / total : 0;
var start = cumulative * circ;
half_cumulative = cumulative + half_fraction;
cumulative += fraction;
var end = cumulative * circ;
self.baseDraw.pie(self,{
config : opts.chartData[i],
s : start,
e : end,
r : radiu,
innerR : 0
})
.css({zIndex:5,cursor:'pointer'})
.attr({move:moveDisplacement,pos:dot[0]+'-'+dot[1]})
.on('mouseover',function(){
this.setOpacity(0.85);
var pos = this.attr('pos').split('-');
self.showTooltip(opts.chartData[i],pos[0],pos[1],((es)/360*100).toFixed(0)+'%')
})
.on('mouseout',function(e){
var elem = e.toElement || e.relatedTarget;
//如果碰到里面的文本或者是提示框不消失
if(!elem||contains(this[0].parentNode,elem)||contains(self.tipC[0],elem))
возвращаться;
self.hideTooltip();
this.setOpacity(1);
})
.on('click',function(){
var m = this.attr('move')
if(m.indexOf('+')>0){
hasSVG
? this.attr({
transform: 'translate(0,0)'
})
: this.css({
left : '0px',
top : '0px'
})
this.attr({move:m.replace('+','')});
}еще{
var s= m.split(',');
hasSVG
? this.attr({
transform: 'translate('+m+')'
})
: this.css({
left : s[0]+'px',
top : s[1]+'px'
})
this.attr({move:m+'+'});
}
})
.appendTo(pieGroup);
self.mainGroup['chart'+i] = {
chart : pieGroup,
show : true
};
self.baseDraw.span(self,{
x : x,
y : y,
fill : '#fff',
'text-anchor':'left'
})
.css({
fontFamily : 'Verdana,Arial,Helvetica,sans-serif',
fontSize : '12px',
position : 'absolute',
color : '#fff',
cursor : 'pointer',
zIndex : 10
})
.addText(name)
.appendTo(pieGroup);
});
},
drawPies : function(){
var self = this,
opts = this.opts,
area = opts.area,
rx = area.centerX,
ry = area.centerY,
total = 0,
data = [],
chartData = opts.chartData,
cumulative = -0.25, // start at top;
circ = 2 * Math.PI,
radiu = mathMin(opts.charts.radius,mathMin(area.areaWidth/2,area.areaHeight/2)),
fraction,
half_cumulative,
half_fraction;
each(chartData,function(i,o){
each(o.data,function(j,d){
data[j]
? data[j] +=mathAbs(d)
: data[j] =mathAbs(d)
});
});
//看有多少个数据来生成来生成内半径
var len = data.length,
innerSpace = radiu / 10;
Rpice = (radiu - innerSpace) / len;
each(data,function(i,d){
var inc = 0;
if(d===0) return;
each(chartData,function(j,o){
if(~~o.data[i]===0)return;
var outR = radiu - Rpice * i,
innerR = radiu - Rpice * (i + 1),
value = ~~o.data[i],
fraction = value / d;
half_fraction = (value/2)/d ,
start = cumulative * circ,
s = inc/d*360,
e = (inc + value)/d*360,
id = 'chart'+j,
piesGroup = self.mainGroup[id]?self.mainGroup[id].chart:self.group(id).appendTo();
!self.mainGroup[id]
&&(self.mainGroup[id] = {chart:piesGroup,show:true});
inc = inc + value;
varname = o.name,
size = calTextLen(name),
dot = angle(radiu,[rx,ry],s+(es)/2,2),
showDot = angle(radiu- Rpice * i,[rx,ry],s+(es)/2,2),
px = dot[0]>rx?1:-1,
py = dot[1]>ry?1:-1;
var x = rx + px*innerSpace + ((dot[0]-rx-px*innerSpace)/len)*(len-i-1)+((dot[0]-rx-px*innerSpace)/len)/2- size.w/2,
y = ry + py*innerSpace +((dot[1]-ry-py*innerSpace)/len)*(len-i-1)+((dot[1]-ry-py*innerSpace)/len)/2- size.h/2;
half_cumulative = cumulative + half_fraction,
cumulative += fraction,
end = cumulative * circ;
self.baseDraw.pie(self,{
config : o,
s : start,
e : end,
r : outR,
innerR : innerR
})
.attr({m : i+'-'+j,data:((es)/360*100).toFixed(0)+'%',pos:showDot[0]+'-'+showDot[1]})
.css({zIndex:5,cursor:'pointer'})
.on('mouseover',function(){
this.setOpacity(0.85);
var pos = this.attr('pos').split('-');
self.showTooltip(o,pos[0],pos[1],this.attr('data'))
})
.on('mouseout',function(e){
var elem = e.toElement || e.relatedTarget;
if(!elem||elem.getAttribute('m')===this[0].getAttribute('m'))
возвращаться;
this.setOpacity(1);
})
.appendTo(piesGroup);
self.baseDraw.span(self,{
x : x,
y : y,
fill : '#fff',
'text-anchor':'left'
})
.attr({m : i+'-'+j})
.css({
fontFamily : 'Verdana,Arial,Helvetica,sans-serif',
fontSize : '12px',
position : 'absolute',
color : '#fff',
cursor : 'pointer',
zIndex : 10
})
.addText(name)
.appendTo(piesGroup);
});
});
},
drawSegment : function(){
var self = this,
opts = this.opts,
draw = opts.draw,
chartData = opts.chartData,
typeIsX = opts.charts.panel==='x',
columnPad = 5,
prev = [],
columnSize = ~~(typeIsX?draw.xPices:draw.yPices) - columnPad * 2;
each(chartData,function(i,c){
if(i in self.hideList)
возвращаться;
var id = 'chart' + i,
segmentGroup = self.mainGroup[id]?self.mainGroup[id].chart:self.group(id).appendTo();
self.mainGroup[id] = {chart : segmentGroup,show : true};
each(c.data,function(j,d){
if(d===null||d===0)
возвращаться;
if(typeIsX){
var start = draw.startX + columnPad,
x = ~~(start + j*draw.xPices).toFixed(0),
y = ~~(draw.startY-(prev[j]?prev[j]:0)).toFixed(0),
size = ~~(d*draw.yPices / draw.feed ).toFixed(0),
path = [
M,
x,
y,
L,
x,
y - size,
L,
x + columnSize,
y - size,
L,
x + columnSize,
y,
тюлень
];
var pos = [x + columnSize/2,y-size];
}еще{
var start = draw.startY - columnPad,
x = ~~(draw.startX+(prev[j]?prev[j]:0)).toFixed(0) ,
y = ~~(start- j*draw.yPices).toFixed(0),
size = ~~(d*draw.xPices / draw.feed ).toFixed(0),
path = [
M,
x,
y,
L,
x + size,
y ,
L,
x + size,
y - columnSize,
L,
x ,
y - columnSize,
тюлень
];
var pos = [x+size/2,y - columnSize];
}
self.baseDraw.path(self,{
border : 0,
isfill : true,
fillColor : c.color,
opacity : 1,
path : path
})
.attr({data:d,pos:pos[0]+'-'+pos[1]})
.on('mouseover',function(){
this.setOpacity(0.85);
var pos = this.attr('pos').split('-');
self.showTooltip(chartData[i],pos[0],pos[1],this.attr('data'))
})
.on('mouseout',function(){
this.setOpacity(1);
})
.css({zIndex:5,cursor:'pointer',left:'0px',top:'0px'})
.appendTo(segmentGroup);
prev[j]
? prev[j] = prev[j] + size
: prev[j] = size;
});
});
},
baseDraw : {
rect : function(o,config){
return o.createElement('rect')
.attr({
rx : config.arc*30 || 5,
ry : config.arc*30 || 5,
width : config.width || 50,
height : config.height || 50,
fill : config.fill || '#fff',
'fill-opacity' : config.opacity || 0.85,
'stroke-width' : config.border || 2,
stroke : config.borderColor || '#606060',
transform : 'translate('+(config.left||0)+','+(config.top||0)+')'
});
},
text : function(o,config){
return o.createElement('text')
.attr(config);
},
span : function(o,config,v){
return o.createElement('text')
.attr(config)
.attr({
y : config.y+(v||15)
});
},
path : function(o,config){
var set = {};
set['stroke-width'] = config.border;
set.stroke = config.borderColor || '#C0C0C0';
set.fill = config.isfill?config.fillColor:'none';
set.d = config.path;
config.opacity
&&(set['fill-opacity'] = config.opacity);
return o.createElement('path')
.attr(set);
},
circle : function(o,config){
var set = {};
set.cx = config.x;
set.cy = config.y;
set['stroke-width'] = 0;
set.stroke = config.borderColor || '#C0C0C0';
set.r = config.r;
set.fill = config.fillColor;
return o.createElement('circle')
.attr(set);
},
square : function(o,config){
var x = config.x,
y = config.y,
r = config.r,
color= config.fillColor,
len = r,
path = [
M,
(x-len).toFixed(0),
(y-len).toFixed(0),
L,
(x+len).toFixed(0),
(y-len).toFixed(0),
(x+len).toFixed(0),
(y+len).toFixed(0),
(x-len).toFixed(0),
(y+len).toFixed(0),
тюлень
];
return o.baseDraw.path(o,{
border : 1,
borderColor : color,
isfill : true,
fillColor : color,
path : path
});
},
triangle : function(o,config){
var x = config.x,
y = config.y,
r = config.r+0.1,
color = config.fillColor,
path = [
M,
x.toFixed(0),
(y-1.33*r).toFixed(0),
L,
(x+r).toFixed(0),
(y+0.67*r).toFixed(0),
(xr).toFixed(0),
(y+0.67*r).toFixed(0),
тюлень
];
return o.baseDraw.path(o,{
border : 1,
borderColor : color,
isfill : true,
fillColor : color,
path : path
});
},
diamond : function(o,config){
var x = config.x,
y = config.y,
r = 1.35*config.r,
color = config.fillColor,
path = [
M,
x.toFixed(0),
(yr).toFixed(0),
L,
(x+r).toFixed(0),
y.toFixed(0),
x.toFixed(0),
(y+r).toFixed(0),
(xr).toFixed(0),
y.toFixed(0),
тюлень
];
return o.baseDraw.path(o,{
border : 1,
borderColor : color,
isfill : true,
fillColor : color,
path : path
});
},
pie : function(o,config){
//config,s,e,r,index
var opts = o.opts,
s = config.s,
r = config.r,
e = config.e - 0.000001,
id = 'chart'+config.index,
area = opts.area,
rx = area.centerX,
ry = area.centerY,
cosStart = mathCos(s),
sinStart = mathSin(s),
cosEnd = mathCos(e),
sinEnd = mathSin(e),
color = config.config.color,
innerR = config.innerR,
longArc = e - s < Math.PI ? 0 : 1,
path = [
M,
rx + r * cosStart,
ry + r * sinStart,
'A',
r,
r,
0,
longArc,
1,
rx + r * cosEnd,
ry + r * sinEnd,
L,
rx + innerR * cosEnd,
ry + innerR * sinEnd,
'A', // arcTo
innerR, // x radius
innerR, // y radius
0, // slanting
longArc, // long or short arc
0, // clockwise
rx + innerR * cosStart,
ry + innerR * sinStart,
'Z'
];
return o.baseDraw.path(o,{
border : 1,
border : '#fff',
isfill : true,
fillColor : color,
opacity : 1,
path : path
})
}
}
};
//---------------------------------------------------------------------------------------------------
//如果是vml 修改smipleChart.prototype中的一些方法
!hasSVG
&&extend(smipleChart.prototype.baseDraw,{
rect : function(o,config){
var attr = {},
css = {};
attr.arcsize = config.arc || 0.2 +'';
if(config.fill==='none'){
attr.filled = 'f'
}еще{
attr.filled = 't';
attr.fillcolor = config.fill || '#fff';
}
attr.strokeWeight = config.border || 2;
attr.strokeColor = config.borderColor || '#606060';
css.width = config.width || 50 +'px';
css.height = config.height || 50 +'px';
css.zIndex = 10;
css.left = config.left||0+'px';
css.top = config.top ||0+'px';
return o.createElement('roundrect')
.attr(attr)
.css(css);
},
text : function(o,config){
return o.createElement('TextBox')
.attr({inset : "2px,2px,2px,2px" })
.css({zIndex:200})
},
span : function(o,config){
return o.createElement('span').
css({
position:'absolute',
left : config.x+'px',
top : config.y+'px'
})
},
path : function(o,config){
var attr = {},
width = o.width,
height = o.height,
css = {
width : width+'px',
height : height+'px'
};
if(config.border===0){
attr.Stroked = 'f';
attr.strokeWeight =0;
}еще{
attr.strokeWeight = config.border||1 ;
}
attr.strokeColor = config.borderColor || "#C0C0C0";
attr.filled = config.isfill?'t':'f';
attr.filled==='t'
&&(attr.fillcolor=config.fillColor||"#C0C0C0");
attr.coordsize = width+','+height;
attr.path = config.path;
var elem = o.createElement()
.attr(attr)
.css(css);
if(config.opacity){
var fill = o.createElement('fill')
.attr({
type : 'fill',
color : config.fillColor||"#C0C0C0",
opacity : config.opacity
})
.appendTo(elem);
//那这个对象的一个属性引用设置透明的元素以后会用到
elem.opacity = fill[0];
}
return elem;
},
circle : function(o,config){
var width = o.width,
height = o.height,
attr = {
strokeWeight : 1,
coordsize : width+','+height,
filled : 't'
},
css ={
width : width+'px',
height : height+'px'
}
x = config.x,
y = config.y,
r = config.r;
attr.strokeColor=attr.fillcolor = config.fillColor
attr.path =[
'wa', // clockwisearcto
x - r, // left
y - r, // top
x + r, // right
y + r, // bottom
x + r, // start x
y, // start y
x + r, // end x
y, // end y
'e' // close
];
return o.createElement()
.attr(attr)
.css(css)
},
pie : function(o,config){
////config,s,e,r,index
var opts = o.opts,
area = opts.area,
r = config.r,
rx = area.centerX,
ry = area.centerY,
innerR= config.innerR||0,
sDot = angle(r,[rx,ry],s,2),
eDot = angle(r,[rx,ry],e,2),
color = config.config.color,
s = config.s,
e = config.e,
e = e - s == 2 * Math.PI ? e - 0.001 : e,
cosStart = mathCos(s),
sinStart = mathSin(s),
cosEnd = mathCos(e),
sinEnd = mathSin(e),
path = [
'wa', // clockwisearcto
(rx - r).toFixed(0), // left
(ry - r).toFixed(0), // top
(rx + r).toFixed(0), // right
(ry + r).toFixed(0), // bottom
(rx + r * cosStart).toFixed(0), // start x
(ry + r * sinStart).toFixed(0), // start y
(rx + r * cosEnd).toFixed(0), // end x
(ry + r * sinEnd).toFixed(0), // end y
'at', // clockwisearcto
(rx - innerR).toFixed(0), // left
(ry - innerR).toFixed(0), // top
(rx + innerR).toFixed(0), // right
(ry + innerR).toFixed(0), // bottom
(rx + innerR * cosEnd).toFixed(0), // start x
(ry + innerR * sinEnd).toFixed(0), // start y
(rx + innerR * cosStart).toFixed(0), // end x
(ry + innerR * sinStart).toFixed(0), // end y
'x', // finish path
'e' // close
];
return o.baseDraw.path(o,{
border : 1,
border : '#fff',
isfill : true,
fillColor : color,
opacity : 1,
path : path
})
}
});
//---------------------------------------------------------------------------------------------------
})(документ);
window.onload = function(){
var t = new Date().getTime();
var config = {
charts : {
type : 'line',
radius : 150,
panel : 'x',
style: {
fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
fontSize: '12px'
}
},
заголовок: {
text: '线性图表',
y: 10,
style: {
color: 'black',
fontSize: '16px'
}
},
subTitle : {
text: '线性图表副标题',
y: 35,
style: {
color: '#111',
fontSize: '12px'
}
},
legend : {
enable : true,
//type : 'lateral', // lateral 横向或lengthwise 纵向
type : 'lateral',
pos : [10,10],
стиль:{
fontFamily : '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
fontSize : '12px',
magin : '0px'
}
},
yUnit : {
text : '线性图表侧标题',
x : 20,
style : {
color : '#111',
fontSize : '12px'
}
},
xUnit : {
units: [
'一月',
'二月',
'Маршировать',
'四月',
'Может',
'Июнь',
'Июль',
'Август',
'Сентябрь',
'十月',
'十一月',
'十二月'
]
},
chartData : [
{
name : 'xcv',
color : '#4572A7',
dotType : 'square',
//data : [11,12,13,15,16,18,17,14,10]
//[1,2,3,5,6,8,7,4,10]
data: [44,-12,-78,100,-13,-4,-26,34]
}, {
name: 'frfr',
color: '#AA4643',
dotType : 'triangle',
data: [-44,12,78,-100,13,4,-56,-34]
}, {
name: 'AAAAA',
color: '#89A54E',
dotType : 'diamond',
data: [null,78,83,null,22,-78,2,44,78]
}, {
name: 'BBBB',
color: '#80699B',
data: [null, 58, 35, null, 52, 47, 26, -55, 39, 123,15,66]
}
]
};
new smipleChart($$('line'),config);
config.charts.type ='area';
config.title.text ='区域图表'
config.subTitle.text='区域图表副标题'
config.yUnit.text ='区域图表侧标题'
config.chartData = [
{
name : 'xcv',
color : '#4572A7',
//data : [0,3,4,5,6,7,8,9,10,11]
data : [11,12,13,14,15,16,-17,18,19,0]
}, {
name: 'frfr',
color: '#AA4643',
data: [44,12,78,100,13,44,56,34]
}, {
name: 'AAAAA',
color: '#89A54E',
data: [null,101,83,null,22,78,88,44,78]
}, {
name: 'BBBB',
color: '#80699B',
data: [null, 58, 35, null, 52, 47, 26, 55, 39, 123,15,66]
}
]
new smipleChart($$('area'),config);
config.title.text ='柱状图表'
config.subTitle.text='柱状图表副标题'
config.yUnit.text ='柱状图表侧标题'
config.charts.type ='columns';
config.chartData =[
{
name : 'xcv',
color : '#4572A7',
//data : [2,3,4,5,6,7,8,9,10,11]
data : [-0.01,-0.62,0,0.55,null,0.78,-0.63,-0.82,null,null,0.33]
}, {
name: 'frfr',
color: '#AA4643',
data: [-0.22,0.82,0.55,1.32,0.33,0.95,null,1,0.65,null,0.78]
}, {
name: 'AAAAA',
color: '#89A54E',
data: [null,0.62,0.34,null,0.63,0,-0.23,-1,0.62,0.45,null,-0.56]
}
]
new smipleChart($$('zhu'),config);
config.charts.panel='y'
new smipleChart($$('zhu1'),config);
config.charts.type ='pie';
config.title.text ='饼图图表'
config.subTitle.text='饼图图表副标题'
config.yUnit.text =''
config.legend.type='lengthwise';
config.chartData =[
{
name : 'aaa',
color : '#4572A7',
data : [433,123,null,66]
}, {
name: 'bbb',
color: '#AA4643',
data: [45,33,33,411]
}, {
name: 'ccc',
color: '#89A54E',
data: [55,null,75,233]
}, {
name: 'ddd',
color: '#80699B',
data: [63,null,100,333]
}
]
config.legend.pos= [680,30]
new smipleChart($$('pie'),config);
config.charts.type ='pies';
config.title.text ='多层饼图图表'
config.subTitle.text='多层饼图图表副标题'
config.legend.type='lateral';
config.legend.pos= [290,400]
new smipleChart($$('pies'),config);
config.chartData =[
{
name : 'xcv',
color : '#4572A7',
data : [111,222,333,null,444,555,56,57,84]
}, {
name: 'frfr',
color: '#AA4643',
data: [845,666,100,null,666,677,56,88,633,55,555]
}, {
name: 'AAAAA',
color: '#89A54E',
data: [555,162,75,null,364,0,637,112,163,615]
}
]
config.charts.type ='line';
config.legend.pos= [10,10]
//
config.yUnit.lineNum = 10;
config.charts.panel = 'x';
config.title.text ='分段图表'
config.subTitle.text='分段图表副标题'
config.yUnit.text ='分段图表侧标题'
config.charts.type ='segment';
new smipleChart($$('segmentx'),config);
config.charts.panel = 'y';
new smipleChart($$('segmenty'),config);
config.yUnit.lineNum = 2;
config.title.text ='比较小的'
config.subTitle.text='只设置了2条线'
config.yUnit.text ='小测标题';
new smipleChart($$('vv'),config);
//alert(new Date().getTime()-t)
}
</script>
</body>
</html>
Другой
The problem of JS floating point accuracy is difficult to solve. Полем Полем Полем Полем Полем Полем Полем Полем
I hope you can give me some advice on limited level. Полем Полем Полем Полем Полем Полем