【发布时间】:2016-09-12 21:50:19
【问题描述】:
我知道您可能想知道自制的条形图?为什么不是现有的图书馆?好吧,我讨厌使用包含 20000 行代码的文件,而只需要 500 行。
哦,这很有趣 :) 主要目标是我将把这个脚本用于我将使用 Phonegap 制作的应用程序。所以尺寸越小越好。
我已经能够绘制条形图,确保它们的宽度相等,并且它们的高度取决于父容器的高度。正如您将在下面的代码中看到的那样,我还在选项中添加了字体大小。由于某些图表将扩展大约 300 像素的高度(例如,将使用默认的 16 像素)。有些只有 50 像素,字体大小为 12 或更小。所以我将条形图容器减少了 3 倍的字体大小(+ 剩余),以确保顶部(数量)和底部(图例 + 标题)有足够的空间
现在我不完全确定如何添加和居中金额。我尝试搜索现有的图表库以检查它是如何呈现的,不幸的是它们都使用画布或 SVG 容器。有什么建议吗?
/* dataset
------------------
add legends
add result / amount
add bottom-border: 8px extra to both sides?
add chart name
*/
(function ($) {
var methods = {
init : function(options) {
return this.each(function() {
var $this = $(this),
dataset = options.dataset,
fontSize = options.fontSize,
widthOfContainer = $this.width(),
heightOfContainer = $this.height() - (3 * (fontSize + 4)), // make room for title (bottom), legend (bottom), amounts (top)
widthOfBar = parseInt(widthOfContainer / options.dataset.length) - 2,
bar;
$this.bind('draw', function(e) {
$this.empty();
var maxValueInDataset = Math.max.apply(Math, dataset.map(function(o){return o.a;})),
heightPerUnit = parseInt(heightOfContainer / maxValueInDataset);
for (var i = 0; i < dataset.length; i++) {
bar = $(document.createElement('div'));
bar.addClass('bar');
bar.css({
'height': parseInt(dataset[i].a * heightPerUnit) + 'px',
'width': parseInt(widthOfBar) + 'px',
'margin-left': parseInt(i * 2 + i * widthOfBar) + 'px',
'bottom': 2 * (fontSize + 4)
});
$this.append(bar);
}
});
$this.trigger('draw');
});
},
draw : function(n) {
$(this).trigger('draw');
}
};
$.fn.chart = function(methodOrOptions) {
if ( methods[methodOrOptions] ) {
return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
// Default to "init"
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tooltip' );
}
};
$(document).ready(function(){
$('div.barchart').chart({
// Add font-size?
fontSize: 14,
name: 'mana cost',
dataset: [
{a: 2, label: '0'},
{a: 8, label: '1'},
{a: 9, label: '2'},
{a: 4, label: '3'},
{a: 7, label: '4'},
{a: 3, label: '5'},
{a: 1, label: '6'},
{a: 1, label: '7'},
{a: 2, label: '8'},
{a: 5, label: '9'}
]
});
});
}( jQuery ));
/* Barchart
========================================================================== */
.barchart {
color: black;
}
/* Bar
========================================================================== */
.bar {
position: absolute;
height: 0px;
width: 0px;
margin-left: 0px;
bottom: 0px;
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding: 20px;">
<div class="barchart" style="height: 100px; position: relative"></div>
</div>
【问题讨论】:
标签: javascript jquery css jquery-plugins