我正在尝试在js中定位直方图的图例。我被卡住的部分是图例的位置:
我在试着把传奇放在右边。
下面是代码的一小段:
var Barchart = function(options){
this.options = options;
this.canvas = options.canvas;
this.ctx = this.canvas.getContext("2d");
this.colors = options.colors;
this.draw = function(){
var maxValue = 0;
for (var categ in this.options.data){
maxValue = Math.max(maxValue,this.options.data[categ]);
}
var canvasActualHeight = this.canvas.height - this.options.padding * 2;
var canvasActualWidth = this.canvas.width - this.options.padding * 2;
//drawing the grid lines
var gridValue = 0;
while (gridValue <= maxValue){
var gridY = canvasActualHeight * (1 - gridValue/maxValue) + this.options.padding;
drawLine(
this.ctx,
0,
gridY,
this.canvas.width,
gridY,
this.options.gridColor
);
//writing grid markers
this.ctx.save();
this.ctx.fillStyle = this.options.gridColor;
this.ctx.font = "bold 10px Arial";
this.ctx.fillText(gridValue, 10,gridY - 2);
this.ctx.restore();
gridValue+=this.options.gridScale;
}
//drawing the bars
var barIndex = 0;
var numberOfBars = Object.keys(this.options.data).length;
var barSize = (canvasActualWidth)/numberOfBars;
for (categ in this.options.data){
var val = this.options.data[categ];
var barHeight = Math.round( canvasActualHeight * val/maxValue) ;
drawBar(
this.ctx,
this.options.padding + barIndex * barSize,
this.canvas.height - barHeight - this.options.padding,
barSize,
barHeight,
this.colors[barIndex%this.colors.length]
);
//drawing series name
this.ctx.save();
this.ctx.textBaseline="bottom";
this.ctx.textAlign="center";
this.ctx.fillStyle = "#000000";
this.ctx.font = "bold 14px Arial";
this.ctx.fillText(this.options.seriesName, this.canvas.width/2,this.canvas.height);
this.ctx.restore();
barIndex++;
}
//draw legend
barIndex = 0;
var legend = document.querySelector("legend[for='myCanvasBAR']");
var ul = document.createElement("ul");
legend.append(ul);
for (categ in this.options.data){
var li = document.createElement("li");
li.style.listStyle = "none";
li.style.borderLeft = "20px solid "+this.colors[barIndex%this.colors.length];
li.style.padding = "5px";
li.textContent = categ;
ul.append(li);
barIndex++;
}
}
}
var MyBARs = {
"10%": 10,
"20%": 31,
"30%": 70,
"40%": 50,
"50%": 30,
"60%": 20,
"70%": 14,
"80%": 17,
"90%": 155,
"100%": 100
};
由于我是js的新手,我就是不明白如何才能在右边或者甚至在横杆下看到图例。
发布于 2018-10-10 05:45:33
我相信像这样的东西应该是有效的:
legend.style.position = "absolute";
legend.style.top = "0px";
legend.style.right = "0px";
相应地调整像素。
https://stackoverflow.com/questions/52729517
复制相似问题