我试图制作JavaScript条形图绘图仪。对于彼此足够接近的值,它的效果非常好。这是输入数组[1,2,3,4,5,6,7]的样子:
我会说技术上这应该是正确的行为,因为它只显示大数字和其余数字之间的差异,但图表失去了它的清晰度。我无法弄清楚如何计算系数,这会将条形调整到适当的尺寸(相对于画布高度更高)。
以下是代码:
function barplot()
{
this.load = function(canvas)
{
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
},
this.makebar = function(width, height, start)
{
this.ctx.beginPath();
this.ctx.strokeStyle = "black";
this.ctx.moveTo(start.x, start.y);
this.ctx.lineTo(start.x,start.y-height);
this.ctx.lineTo(start.x+width, start.y-height);
this.ctx.lineTo(start.x+width,start.y);
this.ctx.stroke();
this.ctx.closePath();
},
this.plot = function(arr)
{
var width = this.canvas.width/arr.length;
var max = Math.max.apply(null,arr);
var min = Math.min.apply(null,arr);
for(var i=0;i<arr.length;i++) // Bar height generated here!
{
var coe = arr[i]/max;
arr[i] = this.canvas.height*coe; // The actual heights!
}
for(var i=0;i<arr.length;i++)
{
this.makebar(width, arr[i], {x:i*width,y:this.canvas.height});
}
}
}
如果有人想尝试,用法也很简单:
var b = new barplot();
b.load(your_canvas_element);
b.plot(array_of_numbers);